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