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