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