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