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