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