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