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