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