]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
Rollup merge of #58150 - GuillaumeGomez:dont-apply-impl-collapse-rules-to-trait-impls...
[rust.git] / src / librustc_typeck / astconv.rs
1 //! Conversion from AST representation of types to the `ty.rs` representation.
2 //! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an
3 //! instance of `AstConv`.
4
5 use errors::{Applicability, DiagnosticId};
6 use hir::{self, GenericArg, GenericArgs};
7 use hir::def::Def;
8 use hir::def_id::DefId;
9 use hir::HirVec;
10 use lint;
11 use middle::resolve_lifetime as rl;
12 use namespace::Namespace;
13 use rustc::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
14 use rustc::traits;
15 use rustc::ty::{self, Ty, TyCtxt, ToPredicate, TypeFoldable};
16 use rustc::ty::{GenericParamDef, GenericParamDefKind};
17 use rustc::ty::subst::{Kind, Subst, Substs};
18 use rustc::ty::wf::object_region_bounds;
19 use rustc_data_structures::sync::Lrc;
20 use rustc_target::spec::abi;
21 use require_c_abi_if_variadic;
22 use smallvec::SmallVec;
23 use syntax::ast;
24 use syntax::feature_gate::{GateIssue, emit_feature_err};
25 use syntax::ptr::P;
26 use syntax::util::lev_distance::find_best_match_for_name;
27 use syntax_pos::{DUMMY_SP, Span, MultiSpan};
28 use util::common::ErrorReported;
29 use util::nodemap::FxHashMap;
30
31 use std::collections::BTreeSet;
32 use std::iter;
33 use std::slice;
34
35 use super::{check_type_alias_enum_variants_enabled};
36 use rustc_data_structures::fx::FxHashSet;
37
38 #[derive(Debug)]
39 pub struct PathSeg(pub DefId, pub usize);
40
41 pub trait AstConv<'gcx, 'tcx> {
42     fn tcx<'a>(&'a self) -> TyCtxt<'a, 'gcx, 'tcx>;
43
44     /// Returns the set of bounds in scope for the type parameter with
45     /// the given id.
46     fn get_type_parameter_bounds(&self, span: Span, def_id: DefId)
47                                  -> Lrc<ty::GenericPredicates<'tcx>>;
48
49     /// What lifetime should we use when a lifetime is omitted (and not elided)?
50     fn re_infer(&self, span: Span, _def: Option<&ty::GenericParamDef>)
51                 -> Option<ty::Region<'tcx>>;
52
53     /// What type should we use when a type is omitted?
54     fn ty_infer(&self, span: Span) -> Ty<'tcx>;
55
56     /// Same as ty_infer, but with a known type parameter definition.
57     fn ty_infer_for_def(&self,
58                         _def: &ty::GenericParamDef,
59                         span: Span) -> Ty<'tcx> {
60         self.ty_infer(span)
61     }
62
63     /// Projecting an associated type from a (potentially)
64     /// higher-ranked trait reference is more complicated, because of
65     /// the possibility of late-bound regions appearing in the
66     /// associated type binding. This is not legal in function
67     /// signatures for that reason. In a function body, we can always
68     /// handle it because we can use inference variables to remove the
69     /// late-bound regions.
70     fn projected_ty_from_poly_trait_ref(&self,
71                                         span: Span,
72                                         item_def_id: DefId,
73                                         poly_trait_ref: ty::PolyTraitRef<'tcx>)
74                                         -> Ty<'tcx>;
75
76     /// Normalize an associated type coming from the user.
77     fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
78
79     /// Invoked when we encounter an error from some prior pass
80     /// (e.g., resolve) that is translated into a ty-error. This is
81     /// used to help suppress derived errors typeck might otherwise
82     /// report.
83     fn set_tainted_by_errors(&self);
84
85     fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
86 }
87
88 struct ConvertedBinding<'tcx> {
89     item_name: ast::Ident,
90     ty: Ty<'tcx>,
91     span: Span,
92 }
93
94 #[derive(PartialEq)]
95 enum GenericArgPosition {
96     Type,
97     Value, // e.g., functions
98     MethodCall,
99 }
100
101 /// Dummy type used for the `Self` of a `TraitRef` created for converting
102 /// a trait object, and which gets removed in `ExistentialTraitRef`.
103 /// This type must not appear anywhere in other converted types.
104 const TRAIT_OBJECT_DUMMY_SELF: ty::TyKind<'static> = ty::Infer(ty::FreshTy(0));
105
106 impl<'o, 'gcx: 'tcx, 'tcx> dyn AstConv<'gcx, 'tcx> + 'o {
107     pub fn ast_region_to_region(&self,
108         lifetime: &hir::Lifetime,
109         def: Option<&ty::GenericParamDef>)
110         -> ty::Region<'tcx>
111     {
112         let tcx = self.tcx();
113         let lifetime_name = |def_id| {
114             tcx.hir().name(tcx.hir().as_local_node_id(def_id).unwrap()).as_interned_str()
115         };
116
117         let r = match tcx.named_region(lifetime.hir_id) {
118             Some(rl::Region::Static) => {
119                 tcx.types.re_static
120             }
121
122             Some(rl::Region::LateBound(debruijn, id, _)) => {
123                 let name = lifetime_name(id);
124                 tcx.mk_region(ty::ReLateBound(debruijn,
125                     ty::BrNamed(id, name)))
126             }
127
128             Some(rl::Region::LateBoundAnon(debruijn, index)) => {
129                 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
130             }
131
132             Some(rl::Region::EarlyBound(index, id, _)) => {
133                 let name = lifetime_name(id);
134                 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion {
135                     def_id: id,
136                     index,
137                     name,
138                 }))
139             }
140
141             Some(rl::Region::Free(scope, id)) => {
142                 let name = lifetime_name(id);
143                 tcx.mk_region(ty::ReFree(ty::FreeRegion {
144                     scope,
145                     bound_region: ty::BrNamed(id, name)
146                 }))
147
148                 // (*) -- not late-bound, won't change
149             }
150
151             None => {
152                 self.re_infer(lifetime.span, def)
153                     .unwrap_or_else(|| {
154                         // This indicates an illegal lifetime
155                         // elision. `resolve_lifetime` should have
156                         // reported an error in this case -- but if
157                         // not, let's error out.
158                         tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
159
160                         // Supply some dummy value. We don't have an
161                         // `re_error`, annoyingly, so use `'static`.
162                         tcx.types.re_static
163                     })
164             }
165         };
166
167         debug!("ast_region_to_region(lifetime={:?}) yields {:?}",
168                lifetime,
169                r);
170
171         r
172     }
173
174     /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
175     /// returns an appropriate set of substitutions for this particular reference to `I`.
176     pub fn ast_path_substs_for_ty(&self,
177         span: Span,
178         def_id: DefId,
179         item_segment: &hir::PathSegment)
180         -> &'tcx Substs<'tcx>
181     {
182         let (substs, assoc_bindings, _) = item_segment.with_generic_args(|generic_args| {
183             self.create_substs_for_ast_path(
184                 span,
185                 def_id,
186                 generic_args,
187                 item_segment.infer_types,
188                 None,
189             )
190         });
191
192         assoc_bindings.first().map(|b| Self::prohibit_assoc_ty_binding(self.tcx(), b.span));
193
194         substs
195     }
196
197     /// Report error if there is an explicit type parameter when using `impl Trait`.
198     fn check_impl_trait(
199         tcx: TyCtxt,
200         span: Span,
201         seg: &hir::PathSegment,
202         generics: &ty::Generics,
203     ) -> bool {
204         let explicit = !seg.infer_types;
205         let impl_trait = generics.params.iter().any(|param| match param.kind {
206             ty::GenericParamDefKind::Type {
207                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait), ..
208             } => true,
209             _ => false,
210         });
211
212         if explicit && impl_trait {
213             let mut err = struct_span_err! {
214                 tcx.sess,
215                 span,
216                 E0632,
217                 "cannot provide explicit type parameters when `impl Trait` is \
218                  used in argument position."
219             };
220
221             err.emit();
222         }
223
224         impl_trait
225     }
226
227     /// Check that the correct number of generic arguments have been provided.
228     /// Used specifically for function calls.
229     pub fn check_generic_arg_count_for_call(
230         tcx: TyCtxt,
231         span: Span,
232         def: &ty::Generics,
233         seg: &hir::PathSegment,
234         is_method_call: bool,
235     ) -> bool {
236         let empty_args = P(hir::GenericArgs {
237             args: HirVec::new(), bindings: HirVec::new(), parenthesized: false,
238         });
239         let suppress_mismatch = Self::check_impl_trait(tcx, span, seg, &def);
240         Self::check_generic_arg_count(
241             tcx,
242             span,
243             def,
244             if let Some(ref args) = seg.args {
245                 args
246             } else {
247                 &empty_args
248             },
249             if is_method_call {
250                 GenericArgPosition::MethodCall
251             } else {
252                 GenericArgPosition::Value
253             },
254             def.parent.is_none() && def.has_self, // `has_self`
255             seg.infer_types || suppress_mismatch, // `infer_types`
256         ).0
257     }
258
259     /// Check that the correct number of generic arguments have been provided.
260     /// This is used both for datatypes and function calls.
261     fn check_generic_arg_count(
262         tcx: TyCtxt,
263         span: Span,
264         def: &ty::Generics,
265         args: &hir::GenericArgs,
266         position: GenericArgPosition,
267         has_self: bool,
268         infer_types: bool,
269     ) -> (bool, Option<Vec<Span>>) {
270         // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
271         // that lifetimes will proceed types. So it suffices to check the number of each generic
272         // arguments in order to validate them with respect to the generic parameters.
273         let param_counts = def.own_counts();
274         let arg_counts = args.own_counts();
275         let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
276
277         let mut defaults: ty::GenericParamCount = Default::default();
278         for param in &def.params {
279             match param.kind {
280                 GenericParamDefKind::Lifetime => {}
281                 GenericParamDefKind::Type { has_default, .. } => {
282                     defaults.types += has_default as usize
283                 }
284             };
285         }
286
287         if position != GenericArgPosition::Type && !args.bindings.is_empty() {
288             AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
289         }
290
291         // Prohibit explicit lifetime arguments if late-bound lifetime parameters are present.
292         if !infer_lifetimes {
293             if let Some(span_late) = def.has_late_bound_regions {
294                 let msg = "cannot specify lifetime arguments explicitly \
295                            if late bound lifetime parameters are present";
296                 let note = "the late bound lifetime parameter is introduced here";
297                 let span = args.args[0].span();
298                 if position == GenericArgPosition::Value
299                     && arg_counts.lifetimes != param_counts.lifetimes {
300                     let mut err = tcx.sess.struct_span_err(span, msg);
301                     err.span_note(span_late, note);
302                     err.emit();
303                     return (true, None);
304                 } else {
305                     let mut multispan = MultiSpan::from_span(span);
306                     multispan.push_span_label(span_late, note.to_string());
307                     tcx.lint_node(lint::builtin::LATE_BOUND_LIFETIME_ARGUMENTS,
308                                   args.args[0].id(), multispan, msg);
309                     return (false, None);
310                 }
311             }
312         }
313
314         let check_kind_count = |kind,
315                                 required,
316                                 permitted,
317                                 provided,
318                                 offset| {
319             // We enforce the following: `required` <= `provided` <= `permitted`.
320             // For kinds without defaults (i.e., lifetimes), `required == permitted`.
321             // For other kinds (i.e., types), `permitted` may be greater than `required`.
322             if required <= provided && provided <= permitted {
323                 return (false, None);
324             }
325
326             // Unfortunately lifetime and type parameter mismatches are typically styled
327             // differently in diagnostics, which means we have a few cases to consider here.
328             let (bound, quantifier) = if required != permitted {
329                 if provided < required {
330                     (required, "at least ")
331                 } else { // provided > permitted
332                     (permitted, "at most ")
333                 }
334             } else {
335                 (required, "")
336             };
337
338             let mut potential_assoc_types: Option<Vec<Span>> = None;
339             let (spans, label) = if required == permitted && provided > permitted {
340                 // In the case when the user has provided too many arguments,
341                 // we want to point to the unexpected arguments.
342                 let spans: Vec<Span> = args.args[offset+permitted .. offset+provided]
343                         .iter()
344                         .map(|arg| arg.span())
345                         .collect();
346                 potential_assoc_types = Some(spans.clone());
347                 (spans, format!( "unexpected {} argument", kind))
348             } else {
349                 (vec![span], format!(
350                     "expected {}{} {} argument{}",
351                     quantifier,
352                     bound,
353                     kind,
354                     if bound != 1 { "s" } else { "" },
355                 ))
356             };
357
358             let mut err = tcx.sess.struct_span_err_with_code(
359                 spans.clone(),
360                 &format!(
361                     "wrong number of {} arguments: expected {}{}, found {}",
362                     kind,
363                     quantifier,
364                     bound,
365                     provided,
366                 ),
367                 DiagnosticId::Error("E0107".into())
368             );
369             for span in spans {
370                 err.span_label(span, label.as_str());
371             }
372             err.emit();
373
374             (provided > required, // `suppress_error`
375              potential_assoc_types)
376         };
377
378         if !infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes {
379             check_kind_count(
380                 "lifetime",
381                 param_counts.lifetimes,
382                 param_counts.lifetimes,
383                 arg_counts.lifetimes,
384                 0,
385             );
386         }
387         if !infer_types
388             || arg_counts.types > param_counts.types - defaults.types - has_self as usize {
389             check_kind_count(
390                 "type",
391                 param_counts.types - defaults.types - has_self as usize,
392                 param_counts.types - has_self as usize,
393                 arg_counts.types,
394                 arg_counts.lifetimes,
395             )
396         } else {
397             (false, None)
398         }
399     }
400
401     /// Creates the relevant generic argument substitutions
402     /// corresponding to a set of generic parameters. This is a
403     /// rather complex little function. Let me try to explain the
404     /// role of each of its parameters:
405     ///
406     /// To start, we are given the `def_id` of the thing we are
407     /// creating the substitutions for, and a partial set of
408     /// substitutions `parent_substs`. In general, the substitutions
409     /// for an item begin with substitutions for all the "parents" of
410     /// that item -- e.g., for a method it might include the
411     /// parameters from the impl.
412     ///
413     /// Therefore, the method begins by walking down these parents,
414     /// starting with the outermost parent and proceed inwards until
415     /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
416     /// first to see if the parent's substitutions are listed in there. If so,
417     /// we can append those and move on. Otherwise, it invokes the
418     /// three callback functions:
419     ///
420     /// - `args_for_def_id`: given the def-id `P`, supplies back the
421     ///   generic arguments that were given to that parent from within
422     ///   the path; so e.g., if you have `<T as Foo>::Bar`, the def-id
423     ///   might refer to the trait `Foo`, and the arguments might be
424     ///   `[T]`. The boolean value indicates whether to infer values
425     ///   for arguments whose values were not explicitly provided.
426     /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
427     ///   instantiate a `Kind`.
428     /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
429     ///   creates a suitable inference variable.
430     pub fn create_substs_for_generic_args<'a, 'b>(
431         tcx: TyCtxt<'a, 'gcx, 'tcx>,
432         def_id: DefId,
433         parent_substs: &[Kind<'tcx>],
434         has_self: bool,
435         self_ty: Option<Ty<'tcx>>,
436         args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs>, bool),
437         provided_kind: impl Fn(&GenericParamDef, &GenericArg) -> Kind<'tcx>,
438         inferred_kind: impl Fn(Option<&[Kind<'tcx>]>, &GenericParamDef, bool) -> Kind<'tcx>,
439     ) -> &'tcx Substs<'tcx> {
440         // Collect the segments of the path; we need to substitute arguments
441         // for parameters throughout the entire path (wherever there are
442         // generic parameters).
443         let mut parent_defs = tcx.generics_of(def_id);
444         let count = parent_defs.count();
445         let mut stack = vec![(def_id, parent_defs)];
446         while let Some(def_id) = parent_defs.parent {
447             parent_defs = tcx.generics_of(def_id);
448             stack.push((def_id, parent_defs));
449         }
450
451         // We manually build up the substitution, rather than using convenience
452         // methods in `subst.rs`, so that we can iterate over the arguments and
453         // parameters in lock-step linearly, instead of trying to match each pair.
454         let mut substs: SmallVec<[Kind<'tcx>; 8]> = SmallVec::with_capacity(count);
455
456         // Iterate over each segment of the path.
457         while let Some((def_id, defs)) = stack.pop() {
458             let mut params = defs.params.iter().peekable();
459
460             // If we have already computed substitutions for parents, we can use those directly.
461             while let Some(&param) = params.peek() {
462                 if let Some(&kind) = parent_substs.get(param.index as usize) {
463                     substs.push(kind);
464                     params.next();
465                 } else {
466                     break;
467                 }
468             }
469
470             // `Self` is handled first, unless it's been handled in `parent_substs`.
471             if has_self {
472                 if let Some(&param) = params.peek() {
473                     if param.index == 0 {
474                         if let GenericParamDefKind::Type { .. } = param.kind {
475                             substs.push(self_ty.map(|ty| ty.into())
476                                 .unwrap_or_else(|| inferred_kind(None, param, true)));
477                             params.next();
478                         }
479                     }
480                 }
481             }
482
483             // Check whether this segment takes generic arguments and the user has provided any.
484             let (generic_args, infer_types) = args_for_def_id(def_id);
485
486             let mut args = generic_args.iter().flat_map(|generic_args| generic_args.args.iter())
487                 .peekable();
488
489             loop {
490                 // We're going to iterate through the generic arguments that the user
491                 // provided, matching them with the generic parameters we expect.
492                 // Mismatches can occur as a result of elided lifetimes, or for malformed
493                 // input. We try to handle both sensibly.
494                 match (args.peek(), params.peek()) {
495                     (Some(&arg), Some(&param)) => {
496                         match (arg, &param.kind) {
497                             (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime)
498                             | (GenericArg::Type(_), GenericParamDefKind::Type { .. }) => {
499                                 substs.push(provided_kind(param, arg));
500                                 args.next();
501                                 params.next();
502                             }
503                             (GenericArg::Lifetime(_), GenericParamDefKind::Type { .. }) => {
504                                 // We expected a type argument, but got a lifetime
505                                 // argument. This is an error, but we need to handle it
506                                 // gracefully so we can report sensible errors. In this
507                                 // case, we're simply going to infer this argument.
508                                 args.next();
509                             }
510                             (GenericArg::Type(_), GenericParamDefKind::Lifetime) => {
511                                 // We expected a lifetime argument, but got a type
512                                 // argument. That means we're inferring the lifetimes.
513                                 substs.push(inferred_kind(None, param, infer_types));
514                                 params.next();
515                             }
516                         }
517                     }
518                     (Some(_), None) => {
519                         // We should never be able to reach this point with well-formed input.
520                         // Getting to this point means the user supplied more arguments than
521                         // there are parameters.
522                         args.next();
523                     }
524                     (None, Some(&param)) => {
525                         // If there are fewer arguments than parameters, it means
526                         // we're inferring the remaining arguments.
527                         match param.kind {
528                             GenericParamDefKind::Lifetime | GenericParamDefKind::Type { .. } => {
529                                 let kind = inferred_kind(Some(&substs), param, infer_types);
530                                 substs.push(kind);
531                             }
532                         }
533                         args.next();
534                         params.next();
535                     }
536                     (None, None) => break,
537                 }
538             }
539         }
540
541         tcx.intern_substs(&substs)
542     }
543
544     /// Given the type/region arguments provided to some path (along with
545     /// an implicit `Self`, if this is a trait reference) returns the complete
546     /// set of substitutions. This may involve applying defaulted type parameters.
547     ///
548     /// Note that the type listing given here is *exactly* what the user provided.
549     fn create_substs_for_ast_path(&self,
550         span: Span,
551         def_id: DefId,
552         generic_args: &hir::GenericArgs,
553         infer_types: bool,
554         self_ty: Option<Ty<'tcx>>)
555         -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>)
556     {
557         // If the type is parameterized by this region, then replace this
558         // region with the current anon region binding (in other words,
559         // whatever & would get replaced with).
560         debug!("create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
561                 generic_args={:?})",
562                def_id, self_ty, generic_args);
563
564         let tcx = self.tcx();
565         let generic_params = tcx.generics_of(def_id);
566
567         // If a self-type was declared, one should be provided.
568         assert_eq!(generic_params.has_self, self_ty.is_some());
569
570         let has_self = generic_params.has_self;
571         let (_, potential_assoc_types) = Self::check_generic_arg_count(
572             tcx,
573             span,
574             &generic_params,
575             &generic_args,
576             GenericArgPosition::Type,
577             has_self,
578             infer_types,
579         );
580
581         let is_object = self_ty.map_or(false, |ty| ty.sty == TRAIT_OBJECT_DUMMY_SELF);
582         let default_needs_object_self = |param: &ty::GenericParamDef| {
583             if let GenericParamDefKind::Type { has_default, .. } = param.kind {
584                 if is_object && has_default {
585                     if tcx.at(span).type_of(param.def_id).has_self_ty() {
586                         // There is no suitable inference default for a type parameter
587                         // that references self, in an object type.
588                         return true;
589                     }
590                 }
591             }
592
593             false
594         };
595
596         let substs = Self::create_substs_for_generic_args(
597             tcx,
598             def_id,
599             &[][..],
600             self_ty.is_some(),
601             self_ty,
602             // Provide the generic args, and whether types should be inferred.
603             |_| (Some(generic_args), infer_types),
604             // Provide substitutions for parameters for which (valid) arguments have been provided.
605             |param, arg| {
606                 match (&param.kind, arg) {
607                     (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
608                         self.ast_region_to_region(&lt, Some(param)).into()
609                     }
610                     (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
611                         self.ast_ty_to_ty(&ty).into()
612                     }
613                     _ => unreachable!(),
614                 }
615             },
616             // Provide substitutions for parameters for which arguments are inferred.
617             |substs, param, infer_types| {
618                 match param.kind {
619                     GenericParamDefKind::Lifetime => tcx.types.re_static.into(),
620                     GenericParamDefKind::Type { has_default, .. } => {
621                         if !infer_types && has_default {
622                             // No type parameter provided, but a default exists.
623
624                             // If we are converting an object type, then the
625                             // `Self` parameter is unknown. However, some of the
626                             // other type parameters may reference `Self` in their
627                             // defaults. This will lead to an ICE if we are not
628                             // careful!
629                             if default_needs_object_self(param) {
630                                 struct_span_err!(tcx.sess, span, E0393,
631                                                     "the type parameter `{}` must be explicitly \
632                                                      specified",
633                                                     param.name)
634                                     .span_label(span,
635                                                 format!("missing reference to `{}`", param.name))
636                                     .note(&format!("because of the default `Self` reference, \
637                                                     type parameters must be specified on object \
638                                                     types"))
639                                     .emit();
640                                 tcx.types.err.into()
641                             } else {
642                                 // This is a default type parameter.
643                                 self.normalize_ty(
644                                     span,
645                                     tcx.at(span).type_of(param.def_id)
646                                        .subst_spanned(tcx, substs.unwrap(), Some(span))
647                                 ).into()
648                             }
649                         } else if infer_types {
650                             // No type parameters were provided, we can infer all.
651                             if !default_needs_object_self(param) {
652                                 self.ty_infer_for_def(param, span).into()
653                             } else {
654                                 self.ty_infer(span).into()
655                             }
656                         } else {
657                             // We've already errored above about the mismatch.
658                             tcx.types.err.into()
659                         }
660                     }
661                 }
662             },
663         );
664
665         let assoc_bindings = generic_args.bindings.iter().map(|binding| {
666             ConvertedBinding {
667                 item_name: binding.ident,
668                 ty: self.ast_ty_to_ty(&binding.ty),
669                 span: binding.span,
670             }
671         }).collect();
672
673         debug!("create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
674                generic_params, self_ty, substs);
675
676         (substs, assoc_bindings, potential_assoc_types)
677     }
678
679     /// Instantiates the path for the given trait reference, assuming that it's
680     /// bound to a valid trait type. Returns the def_id for the defining trait.
681     /// The type _cannot_ be a type other than a trait type.
682     ///
683     /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T=X>`
684     /// are disallowed. Otherwise, they are pushed onto the vector given.
685     pub fn instantiate_mono_trait_ref(&self,
686         trait_ref: &hir::TraitRef,
687         self_ty: Ty<'tcx>)
688         -> ty::TraitRef<'tcx>
689     {
690         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
691
692         self.ast_path_to_mono_trait_ref(trait_ref.path.span,
693                                         trait_ref.trait_def_id(),
694                                         self_ty,
695                                         trait_ref.path.segments.last().unwrap())
696     }
697
698     /// The given trait-ref must actually be a trait.
699     pub(super) fn instantiate_poly_trait_ref_inner(&self,
700         trait_ref: &hir::TraitRef,
701         self_ty: Ty<'tcx>,
702         poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
703         speculative: bool)
704         -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
705     {
706         let trait_def_id = trait_ref.trait_def_id();
707
708         debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
709
710         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
711
712         let (substs, assoc_bindings, potential_assoc_types) = self.create_substs_for_ast_trait_ref(
713             trait_ref.path.span,
714             trait_def_id,
715             self_ty,
716             trait_ref.path.segments.last().unwrap(),
717         );
718         let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
719
720         let mut dup_bindings = FxHashMap::default();
721         poly_projections.extend(assoc_bindings.iter().filter_map(|binding| {
722             // specify type to assert that error was already reported in Err case:
723             let predicate: Result<_, ErrorReported> =
724                 self.ast_type_binding_to_poly_projection_predicate(
725                     trait_ref.ref_id, poly_trait_ref, binding, speculative, &mut dup_bindings);
726             // okay to ignore Err because of ErrorReported (see above)
727             Some((predicate.ok()?, binding.span))
728         }));
729
730         debug!("instantiate_poly_trait_ref({:?}, projections={:?}) -> {:?}",
731                trait_ref, poly_projections, poly_trait_ref);
732         (poly_trait_ref, potential_assoc_types)
733     }
734
735     pub fn instantiate_poly_trait_ref(&self,
736         poly_trait_ref: &hir::PolyTraitRef,
737         self_ty: Ty<'tcx>,
738         poly_projections: &mut Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>)
739         -> (ty::PolyTraitRef<'tcx>, Option<Vec<Span>>)
740     {
741         self.instantiate_poly_trait_ref_inner(&poly_trait_ref.trait_ref, self_ty,
742                                               poly_projections, false)
743     }
744
745     fn ast_path_to_mono_trait_ref(&self,
746                                   span: Span,
747                                   trait_def_id: DefId,
748                                   self_ty: Ty<'tcx>,
749                                   trait_segment: &hir::PathSegment)
750                                   -> ty::TraitRef<'tcx>
751     {
752         let (substs, assoc_bindings, _) =
753             self.create_substs_for_ast_trait_ref(span,
754                                                  trait_def_id,
755                                                  self_ty,
756                                                  trait_segment);
757         assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
758         ty::TraitRef::new(trait_def_id, substs)
759     }
760
761     fn create_substs_for_ast_trait_ref(
762         &self,
763         span: Span,
764         trait_def_id: DefId,
765         self_ty: Ty<'tcx>,
766         trait_segment: &hir::PathSegment,
767     ) -> (&'tcx Substs<'tcx>, Vec<ConvertedBinding<'tcx>>, Option<Vec<Span>>) {
768         debug!("create_substs_for_ast_trait_ref(trait_segment={:?})",
769                trait_segment);
770
771         let trait_def = self.tcx().trait_def(trait_def_id);
772
773         if !self.tcx().features().unboxed_closures &&
774             trait_segment.with_generic_args(|generic_args| generic_args.parenthesized)
775             != trait_def.paren_sugar {
776             // For now, require that parenthetical notation be used only with `Fn()` etc.
777             let msg = if trait_def.paren_sugar {
778                 "the precise format of `Fn`-family traits' type parameters is subject to change. \
779                  Use parenthetical notation (Fn(Foo, Bar) -> Baz) instead"
780             } else {
781                 "parenthetical notation is only stable when used with `Fn`-family traits"
782             };
783             emit_feature_err(&self.tcx().sess.parse_sess, "unboxed_closures",
784                              span, GateIssue::Language, msg);
785         }
786
787         trait_segment.with_generic_args(|generic_args| {
788             self.create_substs_for_ast_path(span,
789                                             trait_def_id,
790                                             generic_args,
791                                             trait_segment.infer_types,
792                                             Some(self_ty))
793         })
794     }
795
796     fn trait_defines_associated_type_named(&self,
797                                            trait_def_id: DefId,
798                                            assoc_name: ast::Ident)
799                                            -> bool
800     {
801         self.tcx().associated_items(trait_def_id).any(|item| {
802             item.kind == ty::AssociatedKind::Type &&
803             self.tcx().hygienic_eq(assoc_name, item.ident, trait_def_id)
804         })
805     }
806
807     fn ast_type_binding_to_poly_projection_predicate(
808         &self,
809         ref_id: ast::NodeId,
810         trait_ref: ty::PolyTraitRef<'tcx>,
811         binding: &ConvertedBinding<'tcx>,
812         speculative: bool,
813         dup_bindings: &mut FxHashMap<DefId, Span>)
814         -> Result<ty::PolyProjectionPredicate<'tcx>, ErrorReported>
815     {
816         let tcx = self.tcx();
817
818         if !speculative {
819             // Given something like `U: SomeTrait<T = X>`, we want to produce a
820             // predicate like `<U as SomeTrait>::T = X`. This is somewhat
821             // subtle in the event that `T` is defined in a supertrait of
822             // `SomeTrait`, because in that case we need to upcast.
823             //
824             // That is, consider this case:
825             //
826             // ```
827             // trait SubTrait: SuperTrait<int> { }
828             // trait SuperTrait<A> { type T; }
829             //
830             // ... B : SubTrait<T=foo> ...
831             // ```
832             //
833             // We want to produce `<B as SuperTrait<int>>::T == foo`.
834
835             // Find any late-bound regions declared in `ty` that are not
836             // declared in the trait-ref. These are not wellformed.
837             //
838             // Example:
839             //
840             //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
841             //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
842             let late_bound_in_trait_ref = tcx.collect_constrained_late_bound_regions(&trait_ref);
843             let late_bound_in_ty =
844                 tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(binding.ty));
845             debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
846             debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
847             for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
848                 let br_name = match *br {
849                     ty::BrNamed(_, name) => name,
850                     _ => {
851                         span_bug!(
852                             binding.span,
853                             "anonymous bound region {:?} in binding but not trait ref",
854                             br);
855                     }
856                 };
857                 struct_span_err!(tcx.sess,
858                                 binding.span,
859                                 E0582,
860                                 "binding for associated type `{}` references lifetime `{}`, \
861                                  which does not appear in the trait input types",
862                                 binding.item_name, br_name)
863                     .emit();
864             }
865         }
866
867         let candidate = if self.trait_defines_associated_type_named(trait_ref.def_id(),
868                                                                     binding.item_name) {
869             // Simple case: X is defined in the current trait.
870             Ok(trait_ref)
871         } else {
872             // Otherwise, we have to walk through the supertraits to find
873             // those that do.
874             let candidates = traits::supertraits(tcx, trait_ref).filter(|r| {
875                 self.trait_defines_associated_type_named(r.def_id(), binding.item_name)
876             });
877             self.one_bound_for_assoc_type(candidates, &trait_ref.to_string(),
878                                           binding.item_name, binding.span)
879         }?;
880
881         let (assoc_ident, def_scope) =
882             tcx.adjust_ident(binding.item_name, candidate.def_id(), ref_id);
883         let assoc_ty = tcx.associated_items(candidate.def_id()).find(|i| {
884             i.kind == ty::AssociatedKind::Type && i.ident.modern() == assoc_ident
885         }).expect("missing associated type");
886
887         if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
888             let msg = format!("associated type `{}` is private", binding.item_name);
889             tcx.sess.span_err(binding.span, &msg);
890         }
891         tcx.check_stability(assoc_ty.def_id, Some(ref_id), binding.span);
892
893         if !speculative {
894             dup_bindings.entry(assoc_ty.def_id)
895                 .and_modify(|prev_span| {
896                     struct_span_err!(self.tcx().sess, binding.span, E0719,
897                                      "the value of the associated type `{}` (from the trait `{}`) \
898                                       is already specified",
899                                      binding.item_name,
900                                      tcx.item_path_str(assoc_ty.container.id()))
901                         .span_label(binding.span, "re-bound here")
902                         .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
903                         .emit();
904                 })
905                 .or_insert(binding.span);
906         }
907
908         Ok(candidate.map_bound(|trait_ref| {
909             ty::ProjectionPredicate {
910                 projection_ty: ty::ProjectionTy::from_ref_and_name(
911                     tcx,
912                     trait_ref,
913                     binding.item_name,
914                 ),
915                 ty: binding.ty,
916             }
917         }))
918     }
919
920     fn ast_path_to_ty(&self,
921         span: Span,
922         did: DefId,
923         item_segment: &hir::PathSegment)
924         -> Ty<'tcx>
925     {
926         let substs = self.ast_path_substs_for_ty(span, did, item_segment);
927         self.normalize_ty(
928             span,
929             self.tcx().at(span).type_of(did).subst(self.tcx(), substs)
930         )
931     }
932
933     /// Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
934     /// removing the dummy `Self` type (`TRAIT_OBJECT_DUMMY_SELF`).
935     fn trait_ref_to_existential(&self, trait_ref: ty::TraitRef<'tcx>)
936                                 -> ty::ExistentialTraitRef<'tcx> {
937         assert_eq!(trait_ref.self_ty().sty, TRAIT_OBJECT_DUMMY_SELF);
938         ty::ExistentialTraitRef::erase_self_ty(self.tcx(), trait_ref)
939     }
940
941     fn conv_object_ty_poly_trait_ref(&self,
942         span: Span,
943         trait_bounds: &[hir::PolyTraitRef],
944         lifetime: &hir::Lifetime)
945         -> Ty<'tcx>
946     {
947         let tcx = self.tcx();
948
949         if trait_bounds.is_empty() {
950             span_err!(tcx.sess, span, E0224,
951                       "at least one non-builtin trait is required for an object type");
952             return tcx.types.err;
953         }
954
955         let mut projection_bounds = Vec::new();
956         let dummy_self = tcx.mk_ty(TRAIT_OBJECT_DUMMY_SELF);
957         let (principal, potential_assoc_types) = self.instantiate_poly_trait_ref(
958             &trait_bounds[0],
959             dummy_self,
960             &mut projection_bounds,
961         );
962         debug!("principal: {:?}", principal);
963
964         for trait_bound in trait_bounds[1..].iter() {
965             // sanity check for non-principal trait bounds
966             self.instantiate_poly_trait_ref(trait_bound,
967                                             dummy_self,
968                                             &mut vec![]);
969         }
970
971         let (mut auto_traits, trait_bounds) = split_auto_traits(tcx, &trait_bounds[1..]);
972
973         if !trait_bounds.is_empty() {
974             let b = &trait_bounds[0];
975             let span = b.trait_ref.path.span;
976             struct_span_err!(self.tcx().sess, span, E0225,
977                 "only auto traits can be used as additional traits in a trait object")
978                 .span_label(span, "non-auto additional trait")
979                 .emit();
980         }
981
982         // Check that there are no gross object safety violations;
983         // most importantly, that the supertraits don't contain `Self`,
984         // to avoid ICEs.
985         let object_safety_violations =
986             tcx.global_tcx().astconv_object_safety_violations(principal.def_id());
987         if !object_safety_violations.is_empty() {
988             tcx.report_object_safety_error(
989                 span, principal.def_id(), object_safety_violations)
990                .emit();
991             return tcx.types.err;
992         }
993
994         // Use a `BTreeSet` to keep output in a more consistent order.
995         let mut associated_types = BTreeSet::default();
996
997         for tr in traits::elaborate_trait_ref(tcx, principal) {
998             debug!("conv_object_ty_poly_trait_ref: observing object predicate `{:?}`", tr);
999             match tr {
1000                 ty::Predicate::Trait(pred) => {
1001                     associated_types.extend(tcx.associated_items(pred.def_id())
1002                                     .filter(|item| item.kind == ty::AssociatedKind::Type)
1003                                     .map(|item| item.def_id));
1004                 }
1005                 ty::Predicate::Projection(pred) => {
1006                     // A `Self` within the original bound will be substituted with a
1007                     // `TRAIT_OBJECT_DUMMY_SELF`, so check for that.
1008                     let references_self =
1009                         pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1010
1011                     // If the projection output contains `Self`, force the user to
1012                     // elaborate it explicitly to avoid a bunch of complexity.
1013                     //
1014                     // The "classicaly useful" case is the following:
1015                     // ```
1016                     //     trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1017                     //         type MyOutput;
1018                     //     }
1019                     // ```
1020                     //
1021                     // Here, the user could theoretically write `dyn MyTrait<Output=X>`,
1022                     // but actually supporting that would "expand" to an infinitely-long type
1023                     // `fix $ Ï„ â†’ dyn MyTrait<MyOutput=X, Output=<Ï„ as MyTrait>::MyOutput`.
1024                     //
1025                     // Instead, we force the user to write `dyn MyTrait<MyOutput=X, Output=X>`,
1026                     // which is uglier but works. See the discussion in #56288 for alternatives.
1027                     if !references_self {
1028                         // Include projections defined on supertraits,
1029                         projection_bounds.push((pred, DUMMY_SP))
1030                     }
1031                 }
1032                 _ => ()
1033             }
1034         }
1035
1036         for (projection_bound, _) in &projection_bounds {
1037             associated_types.remove(&projection_bound.projection_def_id());
1038         }
1039
1040         if !associated_types.is_empty() {
1041             let names = associated_types.iter().map(|item_def_id| {
1042                 let assoc_item = tcx.associated_item(*item_def_id);
1043                 let trait_def_id = assoc_item.container.id();
1044                 format!(
1045                     "`{}` (from the trait `{}`)",
1046                     assoc_item.ident,
1047                     tcx.item_path_str(trait_def_id),
1048                 )
1049             }).collect::<Vec<_>>().join(", ");
1050             let mut err = struct_span_err!(
1051                 tcx.sess,
1052                 span,
1053                 E0191,
1054                 "the value of the associated type{} {} must be specified",
1055                 if associated_types.len() == 1 { "" } else { "s" },
1056                 names,
1057             );
1058             let mut suggest = false;
1059             let mut potential_assoc_types_spans = vec![];
1060             if let Some(potential_assoc_types) = potential_assoc_types {
1061                 if potential_assoc_types.len() == associated_types.len() {
1062                     // Only suggest when the amount of missing associated types is equals to the
1063                     // extra type arguments present, as that gives us a relatively high confidence
1064                     // that the user forgot to give the associtated type's name. The canonical
1065                     // example would be trying to use `Iterator<isize>` instead of
1066                     // `Iterator<Item=isize>`.
1067                     suggest = true;
1068                     potential_assoc_types_spans = potential_assoc_types;
1069                 }
1070             }
1071             let mut suggestions = vec![];
1072             for (i, item_def_id) in associated_types.iter().enumerate() {
1073                 let assoc_item = tcx.associated_item(*item_def_id);
1074                 err.span_label(
1075                     span,
1076                     format!("associated type `{}` must be specified", assoc_item.ident),
1077                 );
1078                 if item_def_id.is_local() {
1079                     err.span_label(
1080                         tcx.def_span(*item_def_id),
1081                         format!("`{}` defined here", assoc_item.ident),
1082                     );
1083                 }
1084                 if suggest {
1085                     if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(
1086                         potential_assoc_types_spans[i],
1087                     ) {
1088                         suggestions.push((
1089                             potential_assoc_types_spans[i],
1090                             format!("{} = {}", assoc_item.ident, snippet),
1091                         ));
1092                     }
1093                 }
1094             }
1095             if !suggestions.is_empty() {
1096                 let msg = format!("if you meant to specify the associated {}, write",
1097                     if suggestions.len() == 1 { "type" } else { "types" });
1098                 err.multipart_suggestion(
1099                     &msg,
1100                     suggestions,
1101                     Applicability::MaybeIncorrect,
1102                 );
1103             }
1104             err.emit();
1105         }
1106
1107         // Erase the `dummy_self` (`TRAIT_OBJECT_DUMMY_SELF`) used above.
1108         let existential_principal = principal.map_bound(|trait_ref| {
1109             self.trait_ref_to_existential(trait_ref)
1110         });
1111         let existential_projections = projection_bounds.iter().map(|(bound, _)| {
1112             bound.map_bound(|b| {
1113                 let trait_ref = self.trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1114                 ty::ExistentialProjection {
1115                     ty: b.ty,
1116                     item_def_id: b.projection_ty.item_def_id,
1117                     substs: trait_ref.substs,
1118                 }
1119             })
1120         });
1121
1122         // Dedup auto traits so that `dyn Trait + Send + Send` is the same as `dyn Trait + Send`.
1123         auto_traits.sort();
1124         auto_traits.dedup();
1125
1126         // Calling `skip_binder` is okay, because the predicates are re-bound.
1127         let principal = if tcx.trait_is_auto(existential_principal.def_id()) {
1128             ty::ExistentialPredicate::AutoTrait(existential_principal.def_id())
1129         } else {
1130             ty::ExistentialPredicate::Trait(*existential_principal.skip_binder())
1131         };
1132         let mut v =
1133             iter::once(principal)
1134             .chain(auto_traits.into_iter().map(ty::ExistentialPredicate::AutoTrait))
1135             .chain(existential_projections
1136                 .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())))
1137             .collect::<SmallVec<[_; 8]>>();
1138         v.sort_by(|a, b| a.stable_cmp(tcx, b));
1139         v.dedup();
1140         let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1141
1142         // Use explicitly-specified region bound.
1143         let region_bound = if !lifetime.is_elided() {
1144             self.ast_region_to_region(lifetime, None)
1145         } else {
1146             self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1147                 if tcx.named_region(lifetime.hir_id).is_some() {
1148                     self.ast_region_to_region(lifetime, None)
1149                 } else {
1150                     self.re_infer(span, None).unwrap_or_else(|| {
1151                         span_err!(tcx.sess, span, E0228,
1152                                   "the lifetime bound for this object type cannot be deduced \
1153                                    from context; please supply an explicit bound");
1154                         tcx.types.re_static
1155                     })
1156                 }
1157             })
1158         };
1159
1160         debug!("region_bound: {:?}", region_bound);
1161
1162         let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1163         debug!("trait_object_type: {:?}", ty);
1164         ty
1165     }
1166
1167     fn report_ambiguous_associated_type(&self,
1168                                         span: Span,
1169                                         type_str: &str,
1170                                         trait_str: &str,
1171                                         name: &str) {
1172         struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type")
1173             .span_suggestion(
1174                 span,
1175                 "use fully-qualified syntax",
1176                 format!("<{} as {}>::{}", type_str, trait_str, name),
1177                 Applicability::HasPlaceholders
1178             ).emit();
1179     }
1180
1181     // Search for a bound on a type parameter which includes the associated item
1182     // given by `assoc_name`. `ty_param_def_id` is the `DefId` for the type parameter
1183     // This function will fail if there are no suitable bounds or there is
1184     // any ambiguity.
1185     fn find_bound_for_assoc_item(&self,
1186                                  ty_param_def_id: DefId,
1187                                  assoc_name: ast::Ident,
1188                                  span: Span)
1189                                  -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1190     {
1191         let tcx = self.tcx();
1192
1193         let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1194         let bounds = predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref());
1195
1196         // Check that there is exactly one way to find an associated type with the
1197         // correct name.
1198         let suitable_bounds = traits::transitive_bounds(tcx, bounds)
1199             .filter(|b| self.trait_defines_associated_type_named(b.def_id(), assoc_name));
1200
1201         let param_node_id = tcx.hir().as_local_node_id(ty_param_def_id).unwrap();
1202         let param_name = tcx.hir().ty_param_name(param_node_id);
1203         self.one_bound_for_assoc_type(suitable_bounds,
1204                                       &param_name.as_str(),
1205                                       assoc_name,
1206                                       span)
1207     }
1208
1209     // Checks that `bounds` contains exactly one element and reports appropriate
1210     // errors otherwise.
1211     fn one_bound_for_assoc_type<I>(&self,
1212                                    mut bounds: I,
1213                                    ty_param_name: &str,
1214                                    assoc_name: ast::Ident,
1215                                    span: Span)
1216         -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1217         where I: Iterator<Item=ty::PolyTraitRef<'tcx>>
1218     {
1219         let bound = match bounds.next() {
1220             Some(bound) => bound,
1221             None => {
1222                 struct_span_err!(self.tcx().sess, span, E0220,
1223                                  "associated type `{}` not found for `{}`",
1224                                  assoc_name,
1225                                  ty_param_name)
1226                   .span_label(span, format!("associated type `{}` not found", assoc_name))
1227                   .emit();
1228                 return Err(ErrorReported);
1229             }
1230         };
1231
1232         if let Some(bound2) = bounds.next() {
1233             let bounds = iter::once(bound).chain(iter::once(bound2)).chain(bounds);
1234             let mut err = struct_span_err!(
1235                 self.tcx().sess, span, E0221,
1236                 "ambiguous associated type `{}` in bounds of `{}`",
1237                 assoc_name,
1238                 ty_param_name);
1239             err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1240
1241             for bound in bounds {
1242                 let bound_span = self.tcx().associated_items(bound.def_id()).find(|item| {
1243                     item.kind == ty::AssociatedKind::Type &&
1244                         self.tcx().hygienic_eq(assoc_name, item.ident, bound.def_id())
1245                 })
1246                 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1247
1248                 if let Some(span) = bound_span {
1249                     err.span_label(span, format!("ambiguous `{}` from `{}`",
1250                                                  assoc_name,
1251                                                  bound));
1252                 } else {
1253                     span_note!(&mut err, span,
1254                                "associated type `{}` could derive from `{}`",
1255                                ty_param_name,
1256                                bound);
1257                 }
1258             }
1259             err.emit();
1260         }
1261
1262         return Ok(bound);
1263     }
1264
1265     // Create a type from a path to an associated type.
1266     // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1267     // and item_segment is the path segment for `D`. We return a type and a def for
1268     // the whole path.
1269     // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1270     // parameter or `Self`.
1271     pub fn associated_path_to_ty(
1272         &self,
1273         ref_id: ast::NodeId,
1274         span: Span,
1275         qself_ty: Ty<'tcx>,
1276         qself_def: Def,
1277         assoc_segment: &hir::PathSegment,
1278         permit_variants: bool,
1279     ) -> (Ty<'tcx>, Def) {
1280         let tcx = self.tcx();
1281         let assoc_ident = assoc_segment.ident;
1282
1283         debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1284
1285         self.prohibit_generics(slice::from_ref(assoc_segment));
1286
1287         // Check if we have an enum variant.
1288         let mut variant_resolution = None;
1289         if let ty::Adt(adt_def, _) = qself_ty.sty {
1290             if adt_def.is_enum() {
1291                 let variant_def = adt_def.variants.iter().find(|vd| {
1292                     tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did)
1293                 });
1294                 if let Some(variant_def) = variant_def {
1295                     let def = Def::Variant(variant_def.did);
1296                     if permit_variants {
1297                         check_type_alias_enum_variants_enabled(tcx, span);
1298                         tcx.check_stability(variant_def.did, Some(ref_id), span);
1299                         return (qself_ty, def);
1300                     } else {
1301                         variant_resolution = Some(def);
1302                     }
1303                 }
1304             }
1305         }
1306
1307         // Find the type of the associated item, and the trait where the associated
1308         // item is declared.
1309         let bound = match (&qself_ty.sty, qself_def) {
1310             (_, Def::SelfTy(Some(_), Some(impl_def_id))) => {
1311                 // `Self` in an impl of a trait -- we have a concrete self type and a
1312                 // trait reference.
1313                 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1314                     Some(trait_ref) => trait_ref,
1315                     None => {
1316                         // A cycle error occurred, most likely.
1317                         return (tcx.types.err, Def::Err);
1318                     }
1319                 };
1320
1321                 let candidates = traits::supertraits(tcx, ty::Binder::bind(trait_ref))
1322                     .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_ident));
1323
1324                 match self.one_bound_for_assoc_type(candidates, "Self", assoc_ident, span) {
1325                     Ok(bound) => bound,
1326                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1327                 }
1328             }
1329             (&ty::Param(_), Def::SelfTy(Some(param_did), None)) |
1330             (&ty::Param(_), Def::TyParam(param_did)) => {
1331                 match self.find_bound_for_assoc_item(param_did, assoc_ident, span) {
1332                     Ok(bound) => bound,
1333                     Err(ErrorReported) => return (tcx.types.err, Def::Err),
1334                 }
1335             }
1336             _ => {
1337                 if variant_resolution.is_some() {
1338                     // Variant in type position
1339                     let msg = format!("expected type, found variant `{}`", assoc_ident);
1340                     tcx.sess.span_err(span, &msg);
1341                 } else if qself_ty.is_enum() {
1342                     // Report as incorrect enum variant rather than ambiguous type.
1343                     let mut err = tcx.sess.struct_span_err(
1344                         span,
1345                         &format!("no variant `{}` on enum `{}`", &assoc_ident.as_str(), qself_ty),
1346                     );
1347                     // Check if it was a typo.
1348                     let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1349                     if let Some(suggested_name) = find_best_match_for_name(
1350                         adt_def.variants.iter().map(|variant| &variant.ident.name),
1351                         &assoc_ident.as_str(),
1352                         None,
1353                     ) {
1354                         err.span_suggestion(
1355                             span,
1356                             "did you mean",
1357                             format!("{}::{}", qself_ty, suggested_name),
1358                             Applicability::MaybeIncorrect,
1359                         );
1360                     } else {
1361                         err.span_label(span, "unknown variant");
1362                     }
1363                     err.emit();
1364                 } else if !qself_ty.references_error() {
1365                     // Don't print `TyErr` to the user.
1366                     self.report_ambiguous_associated_type(span,
1367                                                           &qself_ty.to_string(),
1368                                                           "Trait",
1369                                                           &assoc_ident.as_str());
1370                 }
1371                 return (tcx.types.err, Def::Err);
1372             }
1373         };
1374
1375         let trait_did = bound.def_id();
1376         let (assoc_ident, def_scope) = tcx.adjust_ident(assoc_ident, trait_did, ref_id);
1377         let item = tcx.associated_items(trait_did).find(|i| {
1378             Namespace::from(i.kind) == Namespace::Type &&
1379                 i.ident.modern() == assoc_ident
1380         }).expect("missing associated type");
1381
1382         let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, bound);
1383         let ty = self.normalize_ty(span, ty);
1384
1385         let def = Def::AssociatedTy(item.def_id);
1386         if !item.vis.is_accessible_from(def_scope, tcx) {
1387             let msg = format!("{} `{}` is private", def.kind_name(), assoc_ident);
1388             tcx.sess.span_err(span, &msg);
1389         }
1390         tcx.check_stability(item.def_id, Some(ref_id), span);
1391
1392         if let Some(variant_def) = variant_resolution {
1393             let mut err = tcx.struct_span_lint_node(
1394                 AMBIGUOUS_ASSOCIATED_ITEMS,
1395                 ref_id,
1396                 span,
1397                 "ambiguous associated item",
1398             );
1399
1400             let mut could_refer_to = |def: Def, also| {
1401                 let note_msg = format!("`{}` could{} refer to {} defined here",
1402                                        assoc_ident, also, def.kind_name());
1403                 err.span_note(tcx.def_span(def.def_id()), &note_msg);
1404             };
1405             could_refer_to(variant_def, "");
1406             could_refer_to(def, " also");
1407
1408             err.span_suggestion(
1409                 span,
1410                 "use fully-qualified syntax",
1411                 format!("<{} as {}>::{}", qself_ty, "Trait", assoc_ident),
1412                 Applicability::HasPlaceholders,
1413             ).emit();
1414         }
1415
1416         (ty, def)
1417     }
1418
1419     fn qpath_to_ty(&self,
1420                    span: Span,
1421                    opt_self_ty: Option<Ty<'tcx>>,
1422                    item_def_id: DefId,
1423                    trait_segment: &hir::PathSegment,
1424                    item_segment: &hir::PathSegment)
1425                    -> Ty<'tcx>
1426     {
1427         let tcx = self.tcx();
1428         let trait_def_id = tcx.parent_def_id(item_def_id).unwrap();
1429
1430         self.prohibit_generics(slice::from_ref(item_segment));
1431
1432         let self_ty = if let Some(ty) = opt_self_ty {
1433             ty
1434         } else {
1435             let path_str = tcx.item_path_str(trait_def_id);
1436             self.report_ambiguous_associated_type(span,
1437                                                   "Type",
1438                                                   &path_str,
1439                                                   &item_segment.ident.as_str());
1440             return tcx.types.err;
1441         };
1442
1443         debug!("qpath_to_ty: self_type={:?}", self_ty);
1444
1445         let trait_ref = self.ast_path_to_mono_trait_ref(span,
1446                                                         trait_def_id,
1447                                                         self_ty,
1448                                                         trait_segment);
1449
1450         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1451
1452         self.normalize_ty(span, tcx.mk_projection(item_def_id, trait_ref.substs))
1453     }
1454
1455     pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment>>(
1456             &self, segments: T) -> bool {
1457         let mut has_err = false;
1458         for segment in segments {
1459             segment.with_generic_args(|generic_args| {
1460                 let (mut err_for_lt, mut err_for_ty) = (false, false);
1461                 for arg in &generic_args.args {
1462                     let (mut span_err, span, kind) = match arg {
1463                         hir::GenericArg::Lifetime(lt) => {
1464                             if err_for_lt { continue }
1465                             err_for_lt = true;
1466                             has_err = true;
1467                             (struct_span_err!(self.tcx().sess, lt.span, E0110,
1468                                               "lifetime arguments are not allowed on this entity"),
1469                              lt.span,
1470                              "lifetime")
1471                         }
1472                         hir::GenericArg::Type(ty) => {
1473                             if err_for_ty { continue }
1474                             err_for_ty = true;
1475                             has_err = true;
1476                             (struct_span_err!(self.tcx().sess, ty.span, E0109,
1477                                               "type arguments are not allowed on this entity"),
1478                              ty.span,
1479                              "type")
1480                         }
1481                     };
1482                     span_err.span_label(span, format!("{} argument not allowed", kind))
1483                             .emit();
1484                     if err_for_lt && err_for_ty {
1485                         break;
1486                     }
1487                 }
1488                 for binding in &generic_args.bindings {
1489                     has_err = true;
1490                     Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
1491                     break;
1492                 }
1493             })
1494         }
1495         has_err
1496     }
1497
1498     pub fn prohibit_assoc_ty_binding(tcx: TyCtxt, span: Span) {
1499         let mut err = struct_span_err!(tcx.sess, span, E0229,
1500                                        "associated type bindings are not allowed here");
1501         err.span_label(span, "associated type not allowed here").emit();
1502     }
1503
1504     pub fn def_ids_for_path_segments(&self,
1505                                      segments: &[hir::PathSegment],
1506                                      self_ty: Option<Ty<'tcx>>,
1507                                      def: Def)
1508                                      -> Vec<PathSeg> {
1509         // We need to extract the type parameters supplied by the user in
1510         // the path `path`. Due to the current setup, this is a bit of a
1511         // tricky-process; the problem is that resolve only tells us the
1512         // end-point of the path resolution, and not the intermediate steps.
1513         // Luckily, we can (at least for now) deduce the intermediate steps
1514         // just from the end-point.
1515         //
1516         // There are basically five cases to consider:
1517         //
1518         // 1. Reference to a constructor of a struct:
1519         //
1520         //        struct Foo<T>(...)
1521         //
1522         //    In this case, the parameters are declared in the type space.
1523         //
1524         // 2. Reference to a constructor of an enum variant:
1525         //
1526         //        enum E<T> { Foo(...) }
1527         //
1528         //    In this case, the parameters are defined in the type space,
1529         //    but may be specified either on the type or the variant.
1530         //
1531         // 3. Reference to a fn item or a free constant:
1532         //
1533         //        fn foo<T>() { }
1534         //
1535         //    In this case, the path will again always have the form
1536         //    `a::b::foo::<T>` where only the final segment should have
1537         //    type parameters. However, in this case, those parameters are
1538         //    declared on a value, and hence are in the `FnSpace`.
1539         //
1540         // 4. Reference to a method or an associated constant:
1541         //
1542         //        impl<A> SomeStruct<A> {
1543         //            fn foo<B>(...)
1544         //        }
1545         //
1546         //    Here we can have a path like
1547         //    `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
1548         //    may appear in two places. The penultimate segment,
1549         //    `SomeStruct::<A>`, contains parameters in TypeSpace, and the
1550         //    final segment, `foo::<B>` contains parameters in fn space.
1551         //
1552         // 5. Reference to a local variable
1553         //
1554         //    Local variables can't have any type parameters.
1555         //
1556         // The first step then is to categorize the segments appropriately.
1557
1558         let tcx = self.tcx();
1559
1560         assert!(!segments.is_empty());
1561         let last = segments.len() - 1;
1562
1563         let mut path_segs = vec![];
1564
1565         match def {
1566             // Case 1. Reference to a struct constructor.
1567             Def::StructCtor(def_id, ..) |
1568             Def::SelfCtor(.., def_id) => {
1569                 // Everything but the final segment should have no
1570                 // parameters at all.
1571                 let generics = tcx.generics_of(def_id);
1572                 // Variant and struct constructors use the
1573                 // generics of their parent type definition.
1574                 let generics_def_id = generics.parent.unwrap_or(def_id);
1575                 path_segs.push(PathSeg(generics_def_id, last));
1576             }
1577
1578             // Case 2. Reference to a variant constructor.
1579             Def::Variant(def_id) |
1580             Def::VariantCtor(def_id, ..) => {
1581                 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
1582                 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
1583                     debug_assert!(adt_def.is_enum());
1584                     (adt_def.did, last)
1585                 } else if last >= 1 && segments[last - 1].args.is_some() {
1586                     // Everything but the penultimate segment should have no
1587                     // parameters at all.
1588                     let enum_def_id = tcx.parent_def_id(def_id).unwrap();
1589                     (enum_def_id, last - 1)
1590                 } else {
1591                     // FIXME: lint here recommending `Enum::<...>::Variant` form
1592                     // instead of `Enum::Variant::<...>` form.
1593
1594                     // Everything but the final segment should have no
1595                     // parameters at all.
1596                     let generics = tcx.generics_of(def_id);
1597                     // Variant and struct constructors use the
1598                     // generics of their parent type definition.
1599                     (generics.parent.unwrap_or(def_id), last)
1600                 };
1601                 path_segs.push(PathSeg(generics_def_id, index));
1602             }
1603
1604             // Case 3. Reference to a top-level value.
1605             Def::Fn(def_id) |
1606             Def::Const(def_id) |
1607             Def::Static(def_id, _) => {
1608                 path_segs.push(PathSeg(def_id, last));
1609             }
1610
1611             // Case 4. Reference to a method or associated const.
1612             Def::Method(def_id) |
1613             Def::AssociatedConst(def_id) => {
1614                 if segments.len() >= 2 {
1615                     let generics = tcx.generics_of(def_id);
1616                     path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
1617                 }
1618                 path_segs.push(PathSeg(def_id, last));
1619             }
1620
1621             // Case 5. Local variable, no generics.
1622             Def::Local(..) | Def::Upvar(..) => {}
1623
1624             _ => bug!("unexpected definition: {:?}", def),
1625         }
1626
1627         debug!("path_segs = {:?}", path_segs);
1628
1629         path_segs
1630     }
1631
1632     // Check a type `Path` and convert it to a `Ty`.
1633     pub fn def_to_ty(&self,
1634                      opt_self_ty: Option<Ty<'tcx>>,
1635                      path: &hir::Path,
1636                      permit_variants: bool)
1637                      -> Ty<'tcx> {
1638         let tcx = self.tcx();
1639
1640         debug!("def_to_ty(def={:?}, opt_self_ty={:?}, path_segments={:?})",
1641                path.def, opt_self_ty, path.segments);
1642
1643         let span = path.span;
1644         match path.def {
1645             Def::Existential(did) => {
1646                 // Check for desugared impl trait.
1647                 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
1648                 let item_segment = path.segments.split_last().unwrap();
1649                 self.prohibit_generics(item_segment.1);
1650                 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
1651                 self.normalize_ty(
1652                     span,
1653                     tcx.mk_opaque(did, substs),
1654                 )
1655             }
1656             Def::Enum(did) | Def::TyAlias(did) | Def::Struct(did) |
1657             Def::Union(did) | Def::ForeignTy(did) => {
1658                 assert_eq!(opt_self_ty, None);
1659                 self.prohibit_generics(path.segments.split_last().unwrap().1);
1660                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
1661             }
1662             Def::Variant(_) if permit_variants => {
1663                 // Convert "variant type" as if it were a real type.
1664                 // The resulting `Ty` is type of the variant's enum for now.
1665                 assert_eq!(opt_self_ty, None);
1666
1667                 let path_segs = self.def_ids_for_path_segments(&path.segments, None, path.def);
1668                 let generic_segs: FxHashSet<_> =
1669                     path_segs.iter().map(|PathSeg(_, index)| index).collect();
1670                 self.prohibit_generics(path.segments.iter().enumerate().filter_map(|(index, seg)| {
1671                     if !generic_segs.contains(&index) {
1672                         Some(seg)
1673                     } else {
1674                         None
1675                     }
1676                 }));
1677
1678                 let PathSeg(def_id, index) = path_segs.last().unwrap();
1679                 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
1680             }
1681             Def::TyParam(did) => {
1682                 assert_eq!(opt_self_ty, None);
1683                 self.prohibit_generics(&path.segments);
1684
1685                 let node_id = tcx.hir().as_local_node_id(did).unwrap();
1686                 let item_id = tcx.hir().get_parent_node(node_id);
1687                 let item_def_id = tcx.hir().local_def_id(item_id);
1688                 let generics = tcx.generics_of(item_def_id);
1689                 let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(node_id)];
1690                 tcx.mk_ty_param(index, tcx.hir().name(node_id).as_interned_str())
1691             }
1692             Def::SelfTy(_, Some(def_id)) => {
1693                 // `Self` in impl (we know the concrete type).
1694                 assert_eq!(opt_self_ty, None);
1695                 self.prohibit_generics(&path.segments);
1696                 tcx.at(span).type_of(def_id)
1697             }
1698             Def::SelfTy(Some(_), None) => {
1699                 // `Self` in trait.
1700                 assert_eq!(opt_self_ty, None);
1701                 self.prohibit_generics(&path.segments);
1702                 tcx.mk_self_type()
1703             }
1704             Def::AssociatedTy(def_id) => {
1705                 debug_assert!(path.segments.len() >= 2);
1706                 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
1707                 self.qpath_to_ty(span,
1708                                  opt_self_ty,
1709                                  def_id,
1710                                  &path.segments[path.segments.len() - 2],
1711                                  path.segments.last().unwrap())
1712             }
1713             Def::PrimTy(prim_ty) => {
1714                 assert_eq!(opt_self_ty, None);
1715                 self.prohibit_generics(&path.segments);
1716                 match prim_ty {
1717                     hir::Bool => tcx.types.bool,
1718                     hir::Char => tcx.types.char,
1719                     hir::Int(it) => tcx.mk_mach_int(it),
1720                     hir::Uint(uit) => tcx.mk_mach_uint(uit),
1721                     hir::Float(ft) => tcx.mk_mach_float(ft),
1722                     hir::Str => tcx.mk_str()
1723                 }
1724             }
1725             Def::Err => {
1726                 self.set_tainted_by_errors();
1727                 return self.tcx().types.err;
1728             }
1729             _ => span_bug!(span, "unexpected definition: {:?}", path.def)
1730         }
1731     }
1732
1733     /// Parses the programmer's textual representation of a type into our
1734     /// internal notion of a type.
1735     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty) -> Ty<'tcx> {
1736         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})",
1737                ast_ty.id, ast_ty, ast_ty.node);
1738
1739         let tcx = self.tcx();
1740
1741         let result_ty = match ast_ty.node {
1742             hir::TyKind::Slice(ref ty) => {
1743                 tcx.mk_slice(self.ast_ty_to_ty(&ty))
1744             }
1745             hir::TyKind::Ptr(ref mt) => {
1746                 tcx.mk_ptr(ty::TypeAndMut {
1747                     ty: self.ast_ty_to_ty(&mt.ty),
1748                     mutbl: mt.mutbl
1749                 })
1750             }
1751             hir::TyKind::Rptr(ref region, ref mt) => {
1752                 let r = self.ast_region_to_region(region, None);
1753                 debug!("Ref r={:?}", r);
1754                 let t = self.ast_ty_to_ty(&mt.ty);
1755                 tcx.mk_ref(r, ty::TypeAndMut {ty: t, mutbl: mt.mutbl})
1756             }
1757             hir::TyKind::Never => {
1758                 tcx.types.never
1759             },
1760             hir::TyKind::Tup(ref fields) => {
1761                 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
1762             }
1763             hir::TyKind::BareFn(ref bf) => {
1764                 require_c_abi_if_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
1765                 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl))
1766             }
1767             hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
1768                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
1769             }
1770             hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
1771                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
1772                 let opt_self_ty = maybe_qself.as_ref().map(|qself| {
1773                     self.ast_ty_to_ty(qself)
1774                 });
1775                 self.def_to_ty(opt_self_ty, path, false)
1776             }
1777             hir::TyKind::Def(item_id, ref lifetimes) => {
1778                 let did = tcx.hir().local_def_id(item_id.id);
1779                 self.impl_trait_ty_to_ty(did, lifetimes)
1780             },
1781             hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
1782                 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
1783                 let ty = self.ast_ty_to_ty(qself);
1784
1785                 let def = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.node {
1786                     path.def
1787                 } else {
1788                     Def::Err
1789                 };
1790                 self.associated_path_to_ty(ast_ty.id, ast_ty.span, ty, def, segment, false).0
1791             }
1792             hir::TyKind::Array(ref ty, ref length) => {
1793                 let length_def_id = tcx.hir().local_def_id(length.id);
1794                 let substs = Substs::identity_for_item(tcx, length_def_id);
1795                 let length = ty::LazyConst::Unevaluated(length_def_id, substs);
1796                 let length = tcx.intern_lazy_const(length);
1797                 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
1798                 self.normalize_ty(ast_ty.span, array_ty)
1799             }
1800             hir::TyKind::Typeof(ref _e) => {
1801                 struct_span_err!(tcx.sess, ast_ty.span, E0516,
1802                                  "`typeof` is a reserved keyword but unimplemented")
1803                     .span_label(ast_ty.span, "reserved keyword")
1804                     .emit();
1805
1806                 tcx.types.err
1807             }
1808             hir::TyKind::Infer => {
1809                 // Infer also appears as the type of arguments or return
1810                 // values in a ExprKind::Closure, or as
1811                 // the type of local variables. Both of these cases are
1812                 // handled specially and will not descend into this routine.
1813                 self.ty_infer(ast_ty.span)
1814             }
1815             hir::TyKind::Err => {
1816                 tcx.types.err
1817             }
1818         };
1819
1820         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
1821         result_ty
1822     }
1823
1824     pub fn impl_trait_ty_to_ty(
1825         &self,
1826         def_id: DefId,
1827         lifetimes: &[hir::GenericArg],
1828     ) -> Ty<'tcx> {
1829         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
1830         let tcx = self.tcx();
1831
1832         let generics = tcx.generics_of(def_id);
1833
1834         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
1835         let substs = Substs::for_item(tcx, def_id, |param, _| {
1836             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
1837                 // Our own parameters are the resolved lifetimes.
1838                 match param.kind {
1839                     GenericParamDefKind::Lifetime => {
1840                         if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
1841                             self.ast_region_to_region(lifetime, None).into()
1842                         } else {
1843                             bug!()
1844                         }
1845                     }
1846                     _ => bug!()
1847                 }
1848             } else {
1849                 // Replace all parent lifetimes with 'static.
1850                 match param.kind {
1851                     GenericParamDefKind::Lifetime => {
1852                         tcx.types.re_static.into()
1853                     }
1854                     _ => tcx.mk_param_from_def(param)
1855                 }
1856             }
1857         });
1858         debug!("impl_trait_ty_to_ty: final substs = {:?}", substs);
1859
1860         let ty = tcx.mk_opaque(def_id, substs);
1861         debug!("impl_trait_ty_to_ty: {}", ty);
1862         ty
1863     }
1864
1865     pub fn ty_of_arg(&self,
1866                      ty: &hir::Ty,
1867                      expected_ty: Option<Ty<'tcx>>)
1868                      -> Ty<'tcx>
1869     {
1870         match ty.node {
1871             hir::TyKind::Infer if expected_ty.is_some() => {
1872                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
1873                 expected_ty.unwrap()
1874             }
1875             _ => self.ast_ty_to_ty(ty),
1876         }
1877     }
1878
1879     pub fn ty_of_fn(&self,
1880                     unsafety: hir::Unsafety,
1881                     abi: abi::Abi,
1882                     decl: &hir::FnDecl)
1883                     -> ty::PolyFnSig<'tcx> {
1884         debug!("ty_of_fn");
1885
1886         let tcx = self.tcx();
1887         let input_tys =
1888             decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
1889
1890         let output_ty = match decl.output {
1891             hir::Return(ref output) => self.ast_ty_to_ty(output),
1892             hir::DefaultReturn(..) => tcx.mk_unit(),
1893         };
1894
1895         debug!("ty_of_fn: output_ty={:?}", output_ty);
1896
1897         let bare_fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
1898             input_tys,
1899             output_ty,
1900             decl.variadic,
1901             unsafety,
1902             abi
1903         ));
1904
1905         // Find any late-bound regions declared in return type that do
1906         // not appear in the arguments. These are not well-formed.
1907         //
1908         // Example:
1909         //     for<'a> fn() -> &'a str <-- 'a is bad
1910         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
1911         let inputs = bare_fn_ty.inputs();
1912         let late_bound_in_args = tcx.collect_constrained_late_bound_regions(
1913             &inputs.map_bound(|i| i.to_owned()));
1914         let output = bare_fn_ty.output();
1915         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
1916         for br in late_bound_in_ret.difference(&late_bound_in_args) {
1917             let lifetime_name = match *br {
1918                 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
1919                 ty::BrAnon(_) | ty::BrFresh(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
1920             };
1921             let mut err = struct_span_err!(tcx.sess,
1922                                            decl.output.span(),
1923                                            E0581,
1924                                            "return type references {} \
1925                                             which is not constrained by the fn input types",
1926                                            lifetime_name);
1927             if let ty::BrAnon(_) = *br {
1928                 // The only way for an anonymous lifetime to wind up
1929                 // in the return type but **also** be unconstrained is
1930                 // if it only appears in "associated types" in the
1931                 // input. See #47511 for an example. In this case,
1932                 // though we can easily give a hint that ought to be
1933                 // relevant.
1934                 err.note("lifetimes appearing in an associated type \
1935                           are not considered constrained");
1936             }
1937             err.emit();
1938         }
1939
1940         bare_fn_ty
1941     }
1942
1943     /// Given the bounds on an object, determines what single region bound (if any) we can
1944     /// use to summarize this type. The basic idea is that we will use the bound the user
1945     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
1946     /// for region bounds. It may be that we can derive no bound at all, in which case
1947     /// we return `None`.
1948     fn compute_object_lifetime_bound(&self,
1949         span: Span,
1950         existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>)
1951         -> Option<ty::Region<'tcx>> // if None, use the default
1952     {
1953         let tcx = self.tcx();
1954
1955         debug!("compute_opt_region_bound(existential_predicates={:?})",
1956                existential_predicates);
1957
1958         // No explicit region bound specified. Therefore, examine trait
1959         // bounds and see if we can derive region bounds from those.
1960         let derived_region_bounds =
1961             object_region_bounds(tcx, existential_predicates);
1962
1963         // If there are no derived region bounds, then report back that we
1964         // can find no region bound. The caller will use the default.
1965         if derived_region_bounds.is_empty() {
1966             return None;
1967         }
1968
1969         // If any of the derived region bounds are 'static, that is always
1970         // the best choice.
1971         if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
1972             return Some(tcx.types.re_static);
1973         }
1974
1975         // Determine whether there is exactly one unique region in the set
1976         // of derived region bounds. If so, use that. Otherwise, report an
1977         // error.
1978         let r = derived_region_bounds[0];
1979         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
1980             span_err!(tcx.sess, span, E0227,
1981                       "ambiguous lifetime bound, explicit lifetime bound required");
1982         }
1983         return Some(r);
1984     }
1985 }
1986
1987 /// Divides a list of general trait bounds into two groups: auto traits (e.g., Sync and Send) and
1988 /// the remaining general trait bounds.
1989 fn split_auto_traits<'a, 'b, 'gcx, 'tcx>(tcx: TyCtxt<'a, 'gcx, 'tcx>,
1990                                          trait_bounds: &'b [hir::PolyTraitRef])
1991     -> (Vec<DefId>, Vec<&'b hir::PolyTraitRef>)
1992 {
1993     let (auto_traits, trait_bounds): (Vec<_>, _) = trait_bounds.iter().partition(|bound| {
1994         // Checks whether `trait_did` is an auto trait and adds it to `auto_traits` if so.
1995         match bound.trait_ref.path.def {
1996             Def::Trait(trait_did) if tcx.trait_is_auto(trait_did) => {
1997                 true
1998             }
1999             _ => false
2000         }
2001     });
2002
2003     let auto_traits = auto_traits.into_iter().map(|tr| {
2004         if let Def::Trait(trait_did) = tr.trait_ref.path.def {
2005             trait_did
2006         } else {
2007             unreachable!()
2008         }
2009     }).collect::<Vec<_>>();
2010
2011     (auto_traits, trait_bounds)
2012 }
2013
2014 // A helper struct for conveniently grouping a set of bounds which we pass to
2015 // and return from functions in multiple places.
2016 #[derive(PartialEq, Eq, Clone, Debug)]
2017 pub struct Bounds<'tcx> {
2018     pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
2019     pub implicitly_sized: Option<Span>,
2020     pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span)>,
2021     pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
2022 }
2023
2024 impl<'a, 'gcx, 'tcx> Bounds<'tcx> {
2025     pub fn predicates(&self, tcx: TyCtxt<'a, 'gcx, 'tcx>, param_ty: Ty<'tcx>)
2026                       -> Vec<(ty::Predicate<'tcx>, Span)>
2027     {
2028         // If it could be sized, and is, add the sized predicate.
2029         let sized_predicate = self.implicitly_sized.and_then(|span| {
2030             tcx.lang_items().sized_trait().map(|sized| {
2031                 let trait_ref = ty::TraitRef {
2032                     def_id: sized,
2033                     substs: tcx.mk_substs_trait(param_ty, &[])
2034                 };
2035                 (trait_ref.to_predicate(), span)
2036             })
2037         });
2038
2039         sized_predicate.into_iter().chain(
2040             self.region_bounds.iter().map(|&(region_bound, span)| {
2041                 // Account for the binder being introduced below; no need to shift `param_ty`
2042                 // because, at present at least, it can only refer to early-bound regions.
2043                 let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
2044                 let outlives = ty::OutlivesPredicate(param_ty, region_bound);
2045                 (ty::Binder::dummy(outlives).to_predicate(), span)
2046             }).chain(
2047                 self.trait_bounds.iter().map(|&(bound_trait_ref, span)| {
2048                     (bound_trait_ref.to_predicate(), span)
2049                 })
2050             ).chain(
2051                 self.projection_bounds.iter().map(|&(projection, span)| {
2052                     (projection.to_predicate(), span)
2053                 })
2054             )
2055         ).collect()
2056     }
2057 }