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