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