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