]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
Rollup merge of #72880 - GuillaumeGomez:cleanup-e0637, r=Dylan-DPC
[rust.git] / src / librustc_typeck / astconv.rs
1 // ignore-tidy-filelength FIXME(#67418) Split up this file.
2 //! Conversion from AST representation of types to the `ty.rs` representation.
3 //! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an
4 //! instance of `AstConv`.
5
6 // ignore-tidy-filelength
7
8 use crate::collect::PlaceholderHirTyCollector;
9 use crate::middle::resolve_lifetime as rl;
10 use crate::require_c_abi_if_c_variadic;
11 use rustc_ast::util::lev_distance::find_best_match_for_name;
12 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
13 use rustc_errors::ErrorReported;
14 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId, FatalError};
15 use rustc_hir as hir;
16 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
17 use rustc_hir::def_id::{DefId, LocalDefId};
18 use rustc_hir::intravisit::{walk_generics, Visitor as _};
19 use rustc_hir::lang_items::SizedTraitLangItem;
20 use rustc_hir::{Constness, GenericArg, GenericArgs};
21 use rustc_middle::ty::subst::{self, InternalSubsts, Subst, SubstsRef};
22 use rustc_middle::ty::{
23     self, Const, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness,
24 };
25 use rustc_middle::ty::{GenericParamDef, GenericParamDefKind};
26 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, LATE_BOUND_LIFETIME_ARGUMENTS};
27 use rustc_session::parse::feature_err;
28 use rustc_session::Session;
29 use rustc_span::symbol::{sym, Ident, Symbol};
30 use rustc_span::{MultiSpan, Span, DUMMY_SP};
31 use rustc_target::spec::abi;
32 use rustc_trait_selection::traits;
33 use rustc_trait_selection::traits::astconv_object_safety_violations;
34 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
35 use rustc_trait_selection::traits::wf::object_region_bounds;
36
37 use smallvec::SmallVec;
38 use std::collections::BTreeSet;
39 use std::iter;
40 use std::slice;
41
42 #[derive(Debug)]
43 pub struct PathSeg(pub DefId, pub usize);
44
45 pub trait AstConv<'tcx> {
46     fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
47
48     fn item_def_id(&self) -> Option<DefId>;
49
50     fn default_constness_for_trait_bounds(&self) -> Constness;
51
52     /// Returns predicates in scope of the form `X: Foo`, where `X` is
53     /// a type parameter `X` with the given id `def_id`. This is a
54     /// subset of the full set of predicates.
55     ///
56     /// This is used for one specific purpose: resolving "short-hand"
57     /// associated type references like `T::Item`. In principle, we
58     /// would do that by first getting the full set of predicates in
59     /// scope and then filtering down to find those that apply to `T`,
60     /// but this can lead to cycle errors. The problem is that we have
61     /// to do this resolution *in order to create the predicates in
62     /// the first place*. Hence, we have this "special pass".
63     fn get_type_parameter_bounds(&self, span: Span, def_id: DefId) -> ty::GenericPredicates<'tcx>;
64
65     /// Returns the lifetime to use when a lifetime is omitted (and not elided).
66     fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
67     -> Option<ty::Region<'tcx>>;
68
69     /// Returns the type to use when a type is omitted.
70     fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
71
72     /// Returns `true` if `_` is allowed in type signatures in the current context.
73     fn allow_ty_infer(&self) -> bool;
74
75     /// Returns the const to use when a const is omitted.
76     fn ct_infer(
77         &self,
78         ty: Ty<'tcx>,
79         param: Option<&ty::GenericParamDef>,
80         span: Span,
81     ) -> &'tcx Const<'tcx>;
82
83     /// Projecting an associated type from a (potentially)
84     /// higher-ranked trait reference is more complicated, because of
85     /// the possibility of late-bound regions appearing in the
86     /// associated type binding. This is not legal in function
87     /// signatures for that reason. In a function body, we can always
88     /// handle it because we can use inference variables to remove the
89     /// late-bound regions.
90     fn projected_ty_from_poly_trait_ref(
91         &self,
92         span: Span,
93         item_def_id: DefId,
94         item_segment: &hir::PathSegment<'_>,
95         poly_trait_ref: ty::PolyTraitRef<'tcx>,
96     ) -> Ty<'tcx>;
97
98     /// Normalize an associated type coming from the user.
99     fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
100
101     /// Invoked when we encounter an error from some prior pass
102     /// (e.g., resolve) that is translated into a ty-error. This is
103     /// used to help suppress derived errors typeck might otherwise
104     /// report.
105     fn set_tainted_by_errors(&self);
106
107     fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
108 }
109
110 pub enum SizedByDefault {
111     Yes,
112     No,
113 }
114
115 struct ConvertedBinding<'a, 'tcx> {
116     item_name: Ident,
117     kind: ConvertedBindingKind<'a, 'tcx>,
118     span: Span,
119 }
120
121 enum ConvertedBindingKind<'a, 'tcx> {
122     Equality(Ty<'tcx>),
123     Constraint(&'a [hir::GenericBound<'a>]),
124 }
125
126 /// New-typed boolean indicating whether explicit late-bound lifetimes
127 /// are present in a set of generic arguments.
128 ///
129 /// For example if we have some method `fn f<'a>(&'a self)` implemented
130 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
131 /// is late-bound so should not be provided explicitly. Thus, if `f` is
132 /// instantiated with some generic arguments providing `'a` explicitly,
133 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
134 /// can provide an appropriate diagnostic later.
135 #[derive(Copy, Clone, PartialEq)]
136 pub enum ExplicitLateBound {
137     Yes,
138     No,
139 }
140
141 #[derive(Copy, Clone, PartialEq)]
142 enum GenericArgPosition {
143     Type,
144     Value, // e.g., functions
145     MethodCall,
146 }
147
148 /// A marker denoting that the generic arguments that were
149 /// provided did not match the respective generic parameters.
150 #[derive(Clone, Default)]
151 pub struct GenericArgCountMismatch {
152     /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
153     pub reported: Option<ErrorReported>,
154     /// A list of spans of arguments provided that were not valid.
155     pub invalid_args: Vec<Span>,
156 }
157
158 /// Decorates the result of a generic argument count mismatch
159 /// check with whether explicit late bounds were provided.
160 #[derive(Clone)]
161 pub struct GenericArgCountResult {
162     pub explicit_late_bound: ExplicitLateBound,
163     pub correct: Result<(), GenericArgCountMismatch>,
164 }
165
166 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
167     pub fn ast_region_to_region(
168         &self,
169         lifetime: &hir::Lifetime,
170         def: Option<&ty::GenericParamDef>,
171     ) -> ty::Region<'tcx> {
172         let tcx = self.tcx();
173         let lifetime_name = |def_id| tcx.hir().name(tcx.hir().as_local_hir_id(def_id));
174
175         let r = match tcx.named_region(lifetime.hir_id) {
176             Some(rl::Region::Static) => tcx.lifetimes.re_static,
177
178             Some(rl::Region::LateBound(debruijn, id, _)) => {
179                 let name = lifetime_name(id.expect_local());
180                 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrNamed(id, name)))
181             }
182
183             Some(rl::Region::LateBoundAnon(debruijn, index)) => {
184                 tcx.mk_region(ty::ReLateBound(debruijn, ty::BrAnon(index)))
185             }
186
187             Some(rl::Region::EarlyBound(index, id, _)) => {
188                 let name = lifetime_name(id.expect_local());
189                 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
190             }
191
192             Some(rl::Region::Free(scope, id)) => {
193                 let name = lifetime_name(id.expect_local());
194                 tcx.mk_region(ty::ReFree(ty::FreeRegion {
195                     scope,
196                     bound_region: ty::BrNamed(id, name),
197                 }))
198
199                 // (*) -- not late-bound, won't change
200             }
201
202             None => {
203                 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
204                     // This indicates an illegal lifetime
205                     // elision. `resolve_lifetime` should have
206                     // reported an error in this case -- but if
207                     // not, let's error out.
208                     tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
209
210                     // Supply some dummy value. We don't have an
211                     // `re_error`, annoyingly, so use `'static`.
212                     tcx.lifetimes.re_static
213                 })
214             }
215         };
216
217         debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
218
219         r
220     }
221
222     /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
223     /// returns an appropriate set of substitutions for this particular reference to `I`.
224     pub fn ast_path_substs_for_ty(
225         &self,
226         span: Span,
227         def_id: DefId,
228         item_segment: &hir::PathSegment<'_>,
229     ) -> SubstsRef<'tcx> {
230         let (substs, assoc_bindings, _) = self.create_substs_for_ast_path(
231             span,
232             def_id,
233             &[],
234             item_segment.generic_args(),
235             item_segment.infer_args,
236             None,
237         );
238
239         if let Some(b) = assoc_bindings.first() {
240             Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
241         }
242
243         substs
244     }
245
246     /// Report error if there is an explicit type parameter when using `impl Trait`.
247     fn check_impl_trait(
248         tcx: TyCtxt<'_>,
249         seg: &hir::PathSegment<'_>,
250         generics: &ty::Generics,
251     ) -> bool {
252         let explicit = !seg.infer_args;
253         let impl_trait = generics.params.iter().any(|param| match param.kind {
254             ty::GenericParamDefKind::Type {
255                 synthetic: Some(hir::SyntheticTyParamKind::ImplTrait),
256                 ..
257             } => true,
258             _ => false,
259         });
260
261         if explicit && impl_trait {
262             let spans = seg
263                 .generic_args()
264                 .args
265                 .iter()
266                 .filter_map(|arg| match arg {
267                     GenericArg::Type(_) => Some(arg.span()),
268                     _ => None,
269                 })
270                 .collect::<Vec<_>>();
271
272             let mut err = struct_span_err! {
273                 tcx.sess,
274                 spans.clone(),
275                 E0632,
276                 "cannot provide explicit generic arguments when `impl Trait` is \
277                 used in argument position"
278             };
279
280             for span in spans {
281                 err.span_label(span, "explicit generic argument not allowed");
282             }
283
284             err.emit();
285         }
286
287         impl_trait
288     }
289
290     /// Checks that the correct number of generic arguments have been provided.
291     /// Used specifically for function calls.
292     pub fn check_generic_arg_count_for_call(
293         tcx: TyCtxt<'_>,
294         span: Span,
295         def: &ty::Generics,
296         seg: &hir::PathSegment<'_>,
297         is_method_call: bool,
298     ) -> GenericArgCountResult {
299         let empty_args = hir::GenericArgs::none();
300         let suppress_mismatch = Self::check_impl_trait(tcx, seg, &def);
301         Self::check_generic_arg_count(
302             tcx,
303             span,
304             def,
305             if let Some(ref args) = seg.args { args } else { &empty_args },
306             if is_method_call { GenericArgPosition::MethodCall } else { GenericArgPosition::Value },
307             def.parent.is_none() && def.has_self, // `has_self`
308             seg.infer_args || suppress_mismatch,  // `infer_args`
309         )
310     }
311
312     /// Checks that the correct number of generic arguments have been provided.
313     /// This is used both for datatypes and function calls.
314     fn check_generic_arg_count(
315         tcx: TyCtxt<'_>,
316         span: Span,
317         def: &ty::Generics,
318         args: &hir::GenericArgs<'_>,
319         position: GenericArgPosition,
320         has_self: bool,
321         infer_args: bool,
322     ) -> GenericArgCountResult {
323         // At this stage we are guaranteed that the generic arguments are in the correct order, e.g.
324         // that lifetimes will proceed types. So it suffices to check the number of each generic
325         // arguments in order to validate them with respect to the generic parameters.
326         let param_counts = def.own_counts();
327         let arg_counts = args.own_counts();
328         let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
329
330         let mut defaults: ty::GenericParamCount = Default::default();
331         for param in &def.params {
332             match param.kind {
333                 GenericParamDefKind::Lifetime => {}
334                 GenericParamDefKind::Type { has_default, .. } => {
335                     defaults.types += has_default as usize
336                 }
337                 GenericParamDefKind::Const => {
338                     // FIXME(const_generics:defaults)
339                 }
340             };
341         }
342
343         if position != GenericArgPosition::Type && !args.bindings.is_empty() {
344             AstConv::prohibit_assoc_ty_binding(tcx, args.bindings[0].span);
345         }
346
347         let explicit_late_bound =
348             Self::prohibit_explicit_late_bound_lifetimes(tcx, def, args, position);
349
350         let check_kind_count = |kind,
351                                 required,
352                                 permitted,
353                                 provided,
354                                 offset,
355                                 unexpected_spans: &mut Vec<Span>,
356                                 silent| {
357             debug!(
358                 "check_kind_count: kind: {} required: {} permitted: {} provided: {} offset: {}",
359                 kind, required, permitted, provided, offset
360             );
361             // We enforce the following: `required` <= `provided` <= `permitted`.
362             // For kinds without defaults (e.g.., lifetimes), `required == permitted`.
363             // For other kinds (i.e., types), `permitted` may be greater than `required`.
364             if required <= provided && provided <= permitted {
365                 return Ok(());
366             }
367
368             if silent {
369                 return Err(true);
370             }
371
372             // Unfortunately lifetime and type parameter mismatches are typically styled
373             // differently in diagnostics, which means we have a few cases to consider here.
374             let (bound, quantifier) = if required != permitted {
375                 if provided < required {
376                     (required, "at least ")
377                 } else {
378                     // provided > permitted
379                     (permitted, "at most ")
380                 }
381             } else {
382                 (required, "")
383             };
384
385             let (spans, label) = if required == permitted && provided > permitted {
386                 // In the case when the user has provided too many arguments,
387                 // we want to point to the unexpected arguments.
388                 let spans: Vec<Span> = args.args[offset + permitted..offset + provided]
389                     .iter()
390                     .map(|arg| arg.span())
391                     .collect();
392                 unexpected_spans.extend(spans.clone());
393                 (spans, format!("unexpected {} argument", kind))
394             } else {
395                 (
396                     vec![span],
397                     format!(
398                         "expected {}{} {} argument{}",
399                         quantifier,
400                         bound,
401                         kind,
402                         pluralize!(bound),
403                     ),
404                 )
405             };
406
407             let mut err = tcx.sess.struct_span_err_with_code(
408                 spans.clone(),
409                 &format!(
410                     "wrong number of {} arguments: expected {}{}, found {}",
411                     kind, quantifier, bound, provided,
412                 ),
413                 DiagnosticId::Error("E0107".into()),
414             );
415             for span in spans {
416                 err.span_label(span, label.as_str());
417             }
418             err.emit();
419
420             Err(true)
421         };
422
423         let mut arg_count_correct = Ok(());
424         let mut unexpected_spans = vec![];
425
426         if !infer_lifetimes || arg_counts.lifetimes > param_counts.lifetimes {
427             arg_count_correct = check_kind_count(
428                 "lifetime",
429                 param_counts.lifetimes,
430                 param_counts.lifetimes,
431                 arg_counts.lifetimes,
432                 0,
433                 &mut unexpected_spans,
434                 explicit_late_bound == ExplicitLateBound::Yes,
435             )
436             .and(arg_count_correct);
437         }
438         // FIXME(const_generics:defaults)
439         if !infer_args || arg_counts.consts > param_counts.consts {
440             arg_count_correct = check_kind_count(
441                 "const",
442                 param_counts.consts,
443                 param_counts.consts,
444                 arg_counts.consts,
445                 arg_counts.lifetimes + arg_counts.types,
446                 &mut unexpected_spans,
447                 false,
448             )
449             .and(arg_count_correct);
450         }
451         // Note that type errors are currently be emitted *after* const errors.
452         if !infer_args || arg_counts.types > param_counts.types - defaults.types - has_self as usize
453         {
454             arg_count_correct = check_kind_count(
455                 "type",
456                 param_counts.types - defaults.types - has_self as usize,
457                 param_counts.types - has_self as usize,
458                 arg_counts.types,
459                 arg_counts.lifetimes,
460                 &mut unexpected_spans,
461                 false,
462             )
463             .and(arg_count_correct);
464         }
465
466         GenericArgCountResult {
467             explicit_late_bound,
468             correct: arg_count_correct.map_err(|reported_err| GenericArgCountMismatch {
469                 reported: if reported_err { Some(ErrorReported) } else { None },
470                 invalid_args: unexpected_spans,
471             }),
472         }
473     }
474
475     /// Report an error that a generic argument did not match the generic parameter that was
476     /// expected.
477     fn generic_arg_mismatch_err(sess: &Session, arg: &GenericArg<'_>, kind: &'static str) {
478         let mut err = struct_span_err!(
479             sess,
480             arg.span(),
481             E0747,
482             "{} provided when a {} was expected",
483             arg.descr(),
484             kind,
485         );
486         // This note will be true as long as generic parameters are strictly ordered by their kind.
487         err.note(&format!("{} arguments must be provided before {} arguments", kind, arg.descr()));
488         err.emit();
489     }
490
491     /// Creates the relevant generic argument substitutions
492     /// corresponding to a set of generic parameters. This is a
493     /// rather complex function. Let us try to explain the role
494     /// of each of its parameters:
495     ///
496     /// To start, we are given the `def_id` of the thing we are
497     /// creating the substitutions for, and a partial set of
498     /// substitutions `parent_substs`. In general, the substitutions
499     /// for an item begin with substitutions for all the "parents" of
500     /// that item -- e.g., for a method it might include the
501     /// parameters from the impl.
502     ///
503     /// Therefore, the method begins by walking down these parents,
504     /// starting with the outermost parent and proceed inwards until
505     /// it reaches `def_id`. For each parent `P`, it will check `parent_substs`
506     /// first to see if the parent's substitutions are listed in there. If so,
507     /// we can append those and move on. Otherwise, it invokes the
508     /// three callback functions:
509     ///
510     /// - `args_for_def_id`: given the `DefId` `P`, supplies back the
511     ///   generic arguments that were given to that parent from within
512     ///   the path; so e.g., if you have `<T as Foo>::Bar`, the `DefId`
513     ///   might refer to the trait `Foo`, and the arguments might be
514     ///   `[T]`. The boolean value indicates whether to infer values
515     ///   for arguments whose values were not explicitly provided.
516     /// - `provided_kind`: given the generic parameter and the value from `args_for_def_id`,
517     ///   instantiate a `GenericArg`.
518     /// - `inferred_kind`: if no parameter was provided, and inference is enabled, then
519     ///   creates a suitable inference variable.
520     pub fn create_substs_for_generic_args<'b>(
521         tcx: TyCtxt<'tcx>,
522         def_id: DefId,
523         parent_substs: &[subst::GenericArg<'tcx>],
524         has_self: bool,
525         self_ty: Option<Ty<'tcx>>,
526         arg_count: GenericArgCountResult,
527         args_for_def_id: impl Fn(DefId) -> (Option<&'b GenericArgs<'b>>, bool),
528         mut provided_kind: impl FnMut(&GenericParamDef, &GenericArg<'_>) -> subst::GenericArg<'tcx>,
529         mut inferred_kind: impl FnMut(
530             Option<&[subst::GenericArg<'tcx>]>,
531             &GenericParamDef,
532             bool,
533         ) -> subst::GenericArg<'tcx>,
534     ) -> SubstsRef<'tcx> {
535         // Collect the segments of the path; we need to substitute arguments
536         // for parameters throughout the entire path (wherever there are
537         // generic parameters).
538         let mut parent_defs = tcx.generics_of(def_id);
539         let count = parent_defs.count();
540         let mut stack = vec![(def_id, parent_defs)];
541         while let Some(def_id) = parent_defs.parent {
542             parent_defs = tcx.generics_of(def_id);
543             stack.push((def_id, parent_defs));
544         }
545
546         // We manually build up the substitution, rather than using convenience
547         // methods in `subst.rs`, so that we can iterate over the arguments and
548         // parameters in lock-step linearly, instead of trying to match each pair.
549         let mut substs: SmallVec<[subst::GenericArg<'tcx>; 8]> = SmallVec::with_capacity(count);
550         // Iterate over each segment of the path.
551         while let Some((def_id, defs)) = stack.pop() {
552             let mut params = defs.params.iter().peekable();
553
554             // If we have already computed substitutions for parents, we can use those directly.
555             while let Some(&param) = params.peek() {
556                 if let Some(&kind) = parent_substs.get(param.index as usize) {
557                     substs.push(kind);
558                     params.next();
559                 } else {
560                     break;
561                 }
562             }
563
564             // `Self` is handled first, unless it's been handled in `parent_substs`.
565             if has_self {
566                 if let Some(&param) = params.peek() {
567                     if param.index == 0 {
568                         if let GenericParamDefKind::Type { .. } = param.kind {
569                             substs.push(
570                                 self_ty
571                                     .map(|ty| ty.into())
572                                     .unwrap_or_else(|| inferred_kind(None, param, true)),
573                             );
574                             params.next();
575                         }
576                     }
577                 }
578             }
579
580             // Check whether this segment takes generic arguments and the user has provided any.
581             let (generic_args, infer_args) = args_for_def_id(def_id);
582
583             let mut args =
584                 generic_args.iter().flat_map(|generic_args| generic_args.args.iter()).peekable();
585
586             // If we encounter a type or const when we expect a lifetime, we infer the lifetimes.
587             // If we later encounter a lifetime, we know that the arguments were provided in the
588             // wrong order. `force_infer_lt` records the type or const that forced lifetimes to be
589             // inferred, so we can use it for diagnostics later.
590             let mut force_infer_lt = None;
591
592             loop {
593                 // We're going to iterate through the generic arguments that the user
594                 // provided, matching them with the generic parameters we expect.
595                 // Mismatches can occur as a result of elided lifetimes, or for malformed
596                 // input. We try to handle both sensibly.
597                 match (args.peek(), params.peek()) {
598                     (Some(&arg), Some(&param)) => {
599                         match (arg, &param.kind, arg_count.explicit_late_bound) {
600                             (GenericArg::Lifetime(_), GenericParamDefKind::Lifetime, _)
601                             | (GenericArg::Type(_), GenericParamDefKind::Type { .. }, _)
602                             | (GenericArg::Const(_), GenericParamDefKind::Const, _) => {
603                                 substs.push(provided_kind(param, arg));
604                                 args.next();
605                                 params.next();
606                             }
607                             (
608                                 GenericArg::Type(_) | GenericArg::Const(_),
609                                 GenericParamDefKind::Lifetime,
610                                 _,
611                             ) => {
612                                 // We expected a lifetime argument, but got a type or const
613                                 // argument. That means we're inferring the lifetimes.
614                                 substs.push(inferred_kind(None, param, infer_args));
615                                 force_infer_lt = Some(arg);
616                                 params.next();
617                             }
618                             (GenericArg::Lifetime(_), _, ExplicitLateBound::Yes) => {
619                                 // We've come across a lifetime when we expected something else in
620                                 // the presence of explicit late bounds. This is most likely
621                                 // due to the presence of the explicit bound so we're just going to
622                                 // ignore it.
623                                 args.next();
624                             }
625                             (_, kind, _) => {
626                                 // We expected one kind of parameter, but the user provided
627                                 // another. This is an error. However, if we already know that
628                                 // the arguments don't match up with the parameters, we won't issue
629                                 // an additional error, as the user already knows what's wrong.
630                                 if arg_count.correct.is_ok()
631                                     && arg_count.explicit_late_bound == ExplicitLateBound::No
632                                 {
633                                     Self::generic_arg_mismatch_err(tcx.sess, arg, kind.descr());
634                                 }
635
636                                 // We've reported the error, but we want to make sure that this
637                                 // problem doesn't bubble down and create additional, irrelevant
638                                 // errors. In this case, we're simply going to ignore the argument
639                                 // and any following arguments. The rest of the parameters will be
640                                 // inferred.
641                                 while args.next().is_some() {}
642                             }
643                         }
644                     }
645
646                     (Some(&arg), None) => {
647                         // We should never be able to reach this point with well-formed input.
648                         // There are three situations in which we can encounter this issue.
649                         //
650                         //  1.  The number of arguments is incorrect. In this case, an error
651                         //      will already have been emitted, and we can ignore it.
652                         //  2.  There are late-bound lifetime parameters present, yet the
653                         //      lifetime arguments have also been explicitly specified by the
654                         //      user.
655                         //  3.  We've inferred some lifetimes, which have been provided later (i.e.
656                         //      after a type or const). We want to throw an error in this case.
657
658                         if arg_count.correct.is_ok()
659                             && arg_count.explicit_late_bound == ExplicitLateBound::No
660                         {
661                             let kind = arg.descr();
662                             assert_eq!(kind, "lifetime");
663                             let provided =
664                                 force_infer_lt.expect("lifetimes ought to have been inferred");
665                             Self::generic_arg_mismatch_err(tcx.sess, provided, kind);
666                         }
667
668                         break;
669                     }
670
671                     (None, Some(&param)) => {
672                         // If there are fewer arguments than parameters, it means
673                         // we're inferring the remaining arguments.
674                         substs.push(inferred_kind(Some(&substs), param, infer_args));
675                         params.next();
676                     }
677
678                     (None, None) => break,
679                 }
680             }
681         }
682
683         tcx.intern_substs(&substs)
684     }
685
686     /// Given the type/lifetime/const arguments provided to some path (along with
687     /// an implicit `Self`, if this is a trait reference), returns the complete
688     /// set of substitutions. This may involve applying defaulted type parameters.
689     /// Also returns back constraints on associated types.
690     ///
691     /// Example:
692     ///
693     /// ```
694     /// T: std::ops::Index<usize, Output = u32>
695     /// ^1 ^^^^^^^^^^^^^^2 ^^^^3  ^^^^^^^^^^^4
696     /// ```
697     ///
698     /// 1. The `self_ty` here would refer to the type `T`.
699     /// 2. The path in question is the path to the trait `std::ops::Index`,
700     ///    which will have been resolved to a `def_id`
701     /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
702     ///    parameters are returned in the `SubstsRef`, the associated type bindings like
703     ///    `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
704     ///
705     /// Note that the type listing given here is *exactly* what the user provided.
706     ///
707     /// For (generic) associated types
708     ///
709     /// ```
710     /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
711     /// ```
712     ///
713     /// We have the parent substs are the substs for the parent trait:
714     /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
715     /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
716     /// lists: `[Vec<u8>, u8, 'a]`.
717     fn create_substs_for_ast_path<'a>(
718         &self,
719         span: Span,
720         def_id: DefId,
721         parent_substs: &[subst::GenericArg<'tcx>],
722         generic_args: &'a hir::GenericArgs<'_>,
723         infer_args: bool,
724         self_ty: Option<Ty<'tcx>>,
725     ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, GenericArgCountResult) {
726         // If the type is parameterized by this region, then replace this
727         // region with the current anon region binding (in other words,
728         // whatever & would get replaced with).
729         debug!(
730             "create_substs_for_ast_path(def_id={:?}, self_ty={:?}, \
731                 generic_args={:?})",
732             def_id, self_ty, generic_args
733         );
734
735         let tcx = self.tcx();
736         let generic_params = tcx.generics_of(def_id);
737
738         if generic_params.has_self {
739             if generic_params.parent.is_some() {
740                 // The parent is a trait so it should have at least one subst
741                 // for the `Self` type.
742                 assert!(!parent_substs.is_empty())
743             } else {
744                 // This item (presumably a trait) needs a self-type.
745                 assert!(self_ty.is_some());
746             }
747         } else {
748             assert!(self_ty.is_none() && parent_substs.is_empty());
749         }
750
751         let arg_count = Self::check_generic_arg_count(
752             tcx,
753             span,
754             &generic_params,
755             &generic_args,
756             GenericArgPosition::Type,
757             self_ty.is_some(),
758             infer_args,
759         );
760
761         let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
762         let default_needs_object_self = |param: &ty::GenericParamDef| {
763             if let GenericParamDefKind::Type { has_default, .. } = param.kind {
764                 if is_object && has_default {
765                     let default_ty = tcx.at(span).type_of(param.def_id);
766                     let self_param = tcx.types.self_param;
767                     if default_ty.walk().any(|arg| arg == self_param.into()) {
768                         // There is no suitable inference default for a type parameter
769                         // that references self, in an object type.
770                         return true;
771                     }
772                 }
773             }
774
775             false
776         };
777
778         let mut missing_type_params = vec![];
779         let mut inferred_params = vec![];
780         let substs = Self::create_substs_for_generic_args(
781             tcx,
782             def_id,
783             parent_substs,
784             self_ty.is_some(),
785             self_ty,
786             arg_count.clone(),
787             // Provide the generic args, and whether types should be inferred.
788             |did| {
789                 if did == def_id {
790                     (Some(generic_args), infer_args)
791                 } else {
792                     // The last component of this tuple is unimportant.
793                     (None, false)
794                 }
795             },
796             // Provide substitutions for parameters for which (valid) arguments have been provided.
797             |param, arg| match (&param.kind, arg) {
798                 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
799                     self.ast_region_to_region(&lt, Some(param)).into()
800                 }
801                 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
802                     if let (hir::TyKind::Infer, false) = (&ty.kind, self.allow_ty_infer()) {
803                         inferred_params.push(ty.span);
804                         tcx.types.err.into()
805                     } else {
806                         self.ast_ty_to_ty(&ty).into()
807                     }
808                 }
809                 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
810                     let ct_def_id = tcx.hir().local_def_id(ct.value.hir_id);
811                     ty::Const::from_anon_const(tcx, ct_def_id).into()
812                 }
813                 _ => unreachable!(),
814             },
815             // Provide substitutions for parameters for which arguments are inferred.
816             |substs, param, infer_args| {
817                 match param.kind {
818                     GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
819                     GenericParamDefKind::Type { has_default, .. } => {
820                         if !infer_args && has_default {
821                             // No type parameter provided, but a default exists.
822
823                             // If we are converting an object type, then the
824                             // `Self` parameter is unknown. However, some of the
825                             // other type parameters may reference `Self` in their
826                             // defaults. This will lead to an ICE if we are not
827                             // careful!
828                             if default_needs_object_self(param) {
829                                 missing_type_params.push(param.name.to_string());
830                                 tcx.types.err.into()
831                             } else {
832                                 // This is a default type parameter.
833                                 self.normalize_ty(
834                                     span,
835                                     tcx.at(span).type_of(param.def_id).subst_spanned(
836                                         tcx,
837                                         substs.unwrap(),
838                                         Some(span),
839                                     ),
840                                 )
841                                 .into()
842                             }
843                         } else if infer_args {
844                             // No type parameters were provided, we can infer all.
845                             let param =
846                                 if !default_needs_object_self(param) { Some(param) } else { None };
847                             self.ty_infer(param, span).into()
848                         } else {
849                             // We've already errored above about the mismatch.
850                             tcx.types.err.into()
851                         }
852                     }
853                     GenericParamDefKind::Const => {
854                         let ty = tcx.at(span).type_of(param.def_id);
855                         // FIXME(const_generics:defaults)
856                         if infer_args {
857                             // No const parameters were provided, we can infer all.
858                             self.ct_infer(ty, Some(param), span).into()
859                         } else {
860                             // We've already errored above about the mismatch.
861                             tcx.mk_const(ty::Const { val: ty::ConstKind::Error, ty }).into()
862                         }
863                     }
864                 }
865             },
866         );
867
868         self.complain_about_missing_type_params(
869             missing_type_params,
870             def_id,
871             span,
872             generic_args.args.is_empty(),
873         );
874
875         // Convert associated-type bindings or constraints into a separate vector.
876         // Example: Given this:
877         //
878         //     T: Iterator<Item = u32>
879         //
880         // The `T` is passed in as a self-type; the `Item = u32` is
881         // not a "type parameter" of the `Iterator` trait, but rather
882         // a restriction on `<T as Iterator>::Item`, so it is passed
883         // back separately.
884         let assoc_bindings = generic_args
885             .bindings
886             .iter()
887             .map(|binding| {
888                 let kind = match binding.kind {
889                     hir::TypeBindingKind::Equality { ref ty } => {
890                         ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
891                     }
892                     hir::TypeBindingKind::Constraint { ref bounds } => {
893                         ConvertedBindingKind::Constraint(bounds)
894                     }
895                 };
896                 ConvertedBinding { item_name: binding.ident, kind, span: binding.span }
897             })
898             .collect();
899
900         debug!(
901             "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
902             generic_params, self_ty, substs
903         );
904
905         (substs, assoc_bindings, arg_count)
906     }
907
908     crate fn create_substs_for_associated_item(
909         &self,
910         tcx: TyCtxt<'tcx>,
911         span: Span,
912         item_def_id: DefId,
913         item_segment: &hir::PathSegment<'_>,
914         parent_substs: SubstsRef<'tcx>,
915     ) -> SubstsRef<'tcx> {
916         if tcx.generics_of(item_def_id).params.is_empty() {
917             self.prohibit_generics(slice::from_ref(item_segment));
918
919             parent_substs
920         } else {
921             self.create_substs_for_ast_path(
922                 span,
923                 item_def_id,
924                 parent_substs,
925                 item_segment.generic_args(),
926                 item_segment.infer_args,
927                 None,
928             )
929             .0
930         }
931     }
932
933     /// On missing type parameters, emit an E0393 error and provide a structured suggestion using
934     /// the type parameter's name as a placeholder.
935     fn complain_about_missing_type_params(
936         &self,
937         missing_type_params: Vec<String>,
938         def_id: DefId,
939         span: Span,
940         empty_generic_args: bool,
941     ) {
942         if missing_type_params.is_empty() {
943             return;
944         }
945         let display =
946             missing_type_params.iter().map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
947         let mut err = struct_span_err!(
948             self.tcx().sess,
949             span,
950             E0393,
951             "the type parameter{} {} must be explicitly specified",
952             pluralize!(missing_type_params.len()),
953             display,
954         );
955         err.span_label(
956             self.tcx().def_span(def_id),
957             &format!(
958                 "type parameter{} {} must be specified for this",
959                 pluralize!(missing_type_params.len()),
960                 display,
961             ),
962         );
963         let mut suggested = false;
964         if let (Ok(snippet), true) = (
965             self.tcx().sess.source_map().span_to_snippet(span),
966             // Don't suggest setting the type params if there are some already: the order is
967             // tricky to get right and the user will already know what the syntax is.
968             empty_generic_args,
969         ) {
970             if snippet.ends_with('>') {
971                 // The user wrote `Trait<'a, T>` or similar. To provide an accurate suggestion
972                 // we would have to preserve the right order. For now, as clearly the user is
973                 // aware of the syntax, we do nothing.
974             } else {
975                 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
976                 // least we can clue them to the correct syntax `Iterator<Type>`.
977                 err.span_suggestion(
978                     span,
979                     &format!(
980                         "set the type parameter{plural} to the desired type{plural}",
981                         plural = pluralize!(missing_type_params.len()),
982                     ),
983                     format!("{}<{}>", snippet, missing_type_params.join(", ")),
984                     Applicability::HasPlaceholders,
985                 );
986                 suggested = true;
987             }
988         }
989         if !suggested {
990             err.span_label(
991                 span,
992                 format!(
993                     "missing reference{} to {}",
994                     pluralize!(missing_type_params.len()),
995                     display,
996                 ),
997             );
998         }
999         err.note(
1000             "because of the default `Self` reference, type parameters must be \
1001                   specified on object types",
1002         );
1003         err.emit();
1004     }
1005
1006     /// Instantiates the path for the given trait reference, assuming that it's
1007     /// bound to a valid trait type. Returns the `DefId` of the defining trait.
1008     /// The type _cannot_ be a type other than a trait type.
1009     ///
1010     /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
1011     /// are disallowed. Otherwise, they are pushed onto the vector given.
1012     pub fn instantiate_mono_trait_ref(
1013         &self,
1014         trait_ref: &hir::TraitRef<'_>,
1015         self_ty: Ty<'tcx>,
1016     ) -> ty::TraitRef<'tcx> {
1017         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
1018
1019         self.ast_path_to_mono_trait_ref(
1020             trait_ref.path.span,
1021             trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
1022             self_ty,
1023             trait_ref.path.segments.last().unwrap(),
1024         )
1025     }
1026
1027     /// The given trait-ref must actually be a trait.
1028     pub(super) fn instantiate_poly_trait_ref_inner(
1029         &self,
1030         trait_ref: &hir::TraitRef<'_>,
1031         span: Span,
1032         constness: Constness,
1033         self_ty: Ty<'tcx>,
1034         bounds: &mut Bounds<'tcx>,
1035         speculative: bool,
1036     ) -> GenericArgCountResult {
1037         let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
1038
1039         debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
1040
1041         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
1042
1043         let (substs, assoc_bindings, arg_count) = self.create_substs_for_ast_trait_ref(
1044             trait_ref.path.span,
1045             trait_def_id,
1046             self_ty,
1047             trait_ref.path.segments.last().unwrap(),
1048         );
1049         let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
1050
1051         bounds.trait_bounds.push((poly_trait_ref, span, constness));
1052
1053         let mut dup_bindings = FxHashMap::default();
1054         for binding in &assoc_bindings {
1055             // Specify type to assert that error was already reported in `Err` case.
1056             let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
1057                 trait_ref.hir_ref_id,
1058                 poly_trait_ref,
1059                 binding,
1060                 bounds,
1061                 speculative,
1062                 &mut dup_bindings,
1063                 binding.span,
1064             );
1065             // Okay to ignore `Err` because of `ErrorReported` (see above).
1066         }
1067
1068         debug!(
1069             "instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
1070             trait_ref, bounds, poly_trait_ref
1071         );
1072
1073         arg_count
1074     }
1075
1076     /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
1077     /// a full trait reference. The resulting trait reference is returned. This may also generate
1078     /// auxiliary bounds, which are added to `bounds`.
1079     ///
1080     /// Example:
1081     ///
1082     /// ```
1083     /// poly_trait_ref = Iterator<Item = u32>
1084     /// self_ty = Foo
1085     /// ```
1086     ///
1087     /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
1088     ///
1089     /// **A note on binders:** against our usual convention, there is an implied bounder around
1090     /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
1091     /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
1092     /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
1093     /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
1094     /// however.
1095     pub fn instantiate_poly_trait_ref(
1096         &self,
1097         poly_trait_ref: &hir::PolyTraitRef<'_>,
1098         constness: Constness,
1099         self_ty: Ty<'tcx>,
1100         bounds: &mut Bounds<'tcx>,
1101     ) -> GenericArgCountResult {
1102         self.instantiate_poly_trait_ref_inner(
1103             &poly_trait_ref.trait_ref,
1104             poly_trait_ref.span,
1105             constness,
1106             self_ty,
1107             bounds,
1108             false,
1109         )
1110     }
1111
1112     fn ast_path_to_mono_trait_ref(
1113         &self,
1114         span: Span,
1115         trait_def_id: DefId,
1116         self_ty: Ty<'tcx>,
1117         trait_segment: &hir::PathSegment<'_>,
1118     ) -> ty::TraitRef<'tcx> {
1119         let (substs, assoc_bindings, _) =
1120             self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
1121         if let Some(b) = assoc_bindings.first() {
1122             AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span);
1123         }
1124         ty::TraitRef::new(trait_def_id, substs)
1125     }
1126
1127     /// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
1128     /// an error and attempt to build a reasonable structured suggestion.
1129     fn complain_about_internal_fn_trait(
1130         &self,
1131         span: Span,
1132         trait_def_id: DefId,
1133         trait_segment: &'a hir::PathSegment<'a>,
1134     ) {
1135         let trait_def = self.tcx().trait_def(trait_def_id);
1136
1137         if !self.tcx().features().unboxed_closures
1138             && trait_segment.generic_args().parenthesized != trait_def.paren_sugar
1139         {
1140             let sess = &self.tcx().sess.parse_sess;
1141             // For now, require that parenthetical notation be used only with `Fn()` etc.
1142             let (msg, sugg) = if trait_def.paren_sugar {
1143                 (
1144                     "the precise format of `Fn`-family traits' type parameters is subject to \
1145                      change",
1146                     Some(format!(
1147                         "{}{} -> {}",
1148                         trait_segment.ident,
1149                         trait_segment
1150                             .args
1151                             .as_ref()
1152                             .and_then(|args| args.args.get(0))
1153                             .and_then(|arg| match arg {
1154                                 hir::GenericArg::Type(ty) => match ty.kind {
1155                                     hir::TyKind::Tup(t) => t
1156                                         .iter()
1157                                         .map(|e| sess.source_map().span_to_snippet(e.span))
1158                                         .collect::<Result<Vec<_>, _>>()
1159                                         .map(|a| a.join(", ")),
1160                                     _ => sess.source_map().span_to_snippet(ty.span),
1161                                 }
1162                                 .map(|s| format!("({})", s))
1163                                 .ok(),
1164                                 _ => None,
1165                             })
1166                             .unwrap_or_else(|| "()".to_string()),
1167                         trait_segment
1168                             .generic_args()
1169                             .bindings
1170                             .iter()
1171                             .find_map(|b| match (b.ident.as_str() == "Output", &b.kind) {
1172                                 (true, hir::TypeBindingKind::Equality { ty }) => {
1173                                     sess.source_map().span_to_snippet(ty.span).ok()
1174                                 }
1175                                 _ => None,
1176                             })
1177                             .unwrap_or_else(|| "()".to_string()),
1178                     )),
1179                 )
1180             } else {
1181                 ("parenthetical notation is only stable when used with `Fn`-family traits", None)
1182             };
1183             let mut err = feature_err(sess, sym::unboxed_closures, span, msg);
1184             if let Some(sugg) = sugg {
1185                 let msg = "use parenthetical notation instead";
1186                 err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1187             }
1188             err.emit();
1189         }
1190     }
1191
1192     fn create_substs_for_ast_trait_ref<'a>(
1193         &self,
1194         span: Span,
1195         trait_def_id: DefId,
1196         self_ty: Ty<'tcx>,
1197         trait_segment: &'a hir::PathSegment<'a>,
1198     ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, GenericArgCountResult) {
1199         debug!("create_substs_for_ast_trait_ref(trait_segment={:?})", trait_segment);
1200
1201         self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
1202
1203         self.create_substs_for_ast_path(
1204             span,
1205             trait_def_id,
1206             &[],
1207             trait_segment.generic_args(),
1208             trait_segment.infer_args,
1209             Some(self_ty),
1210         )
1211     }
1212
1213     fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
1214         self.tcx()
1215             .associated_items(trait_def_id)
1216             .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
1217             .is_some()
1218     }
1219
1220     // Returns `true` if a bounds list includes `?Sized`.
1221     pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool {
1222         let tcx = self.tcx();
1223
1224         // Try to find an unbound in bounds.
1225         let mut unbound = None;
1226         for ab in ast_bounds {
1227             if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1228                 if unbound.is_none() {
1229                     unbound = Some(&ptr.trait_ref);
1230                 } else {
1231                     struct_span_err!(
1232                         tcx.sess,
1233                         span,
1234                         E0203,
1235                         "type parameter has more than one relaxed default \
1236                         bound, only one is supported"
1237                     )
1238                     .emit();
1239                 }
1240             }
1241         }
1242
1243         let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1244         match unbound {
1245             Some(tpb) => {
1246                 // FIXME(#8559) currently requires the unbound to be built-in.
1247                 if let Ok(kind_id) = kind_id {
1248                     if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
1249                         tcx.sess.span_warn(
1250                             span,
1251                             "default bound relaxed for a type parameter, but \
1252                              this does nothing because the given bound is not \
1253                              a default; only `?Sized` is supported",
1254                         );
1255                     }
1256                 }
1257             }
1258             _ if kind_id.is_ok() => {
1259                 return false;
1260             }
1261             // No lang item for `Sized`, so we can't add it as a bound.
1262             None => {}
1263         }
1264
1265         true
1266     }
1267
1268     /// This helper takes a *converted* parameter type (`param_ty`)
1269     /// and an *unconverted* list of bounds:
1270     ///
1271     /// ```text
1272     /// fn foo<T: Debug>
1273     ///        ^  ^^^^^ `ast_bounds` parameter, in HIR form
1274     ///        |
1275     ///        `param_ty`, in ty form
1276     /// ```
1277     ///
1278     /// It adds these `ast_bounds` into the `bounds` structure.
1279     ///
1280     /// **A note on binders:** there is an implied binder around
1281     /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
1282     /// for more details.
1283     fn add_bounds(
1284         &self,
1285         param_ty: Ty<'tcx>,
1286         ast_bounds: &[hir::GenericBound<'_>],
1287         bounds: &mut Bounds<'tcx>,
1288     ) {
1289         let mut trait_bounds = Vec::new();
1290         let mut region_bounds = Vec::new();
1291
1292         let constness = self.default_constness_for_trait_bounds();
1293         for ast_bound in ast_bounds {
1294             match *ast_bound {
1295                 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
1296                     trait_bounds.push((b, constness))
1297                 }
1298                 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::MaybeConst) => {
1299                     trait_bounds.push((b, Constness::NotConst))
1300                 }
1301                 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1302                 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
1303             }
1304         }
1305
1306         for (bound, constness) in trait_bounds {
1307             let _ = self.instantiate_poly_trait_ref(bound, constness, param_ty, bounds);
1308         }
1309
1310         bounds.region_bounds.extend(
1311             region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span)),
1312         );
1313     }
1314
1315     /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1316     /// The self-type for the bounds is given by `param_ty`.
1317     ///
1318     /// Example:
1319     ///
1320     /// ```
1321     /// fn foo<T: Bar + Baz>() { }
1322     ///        ^  ^^^^^^^^^ ast_bounds
1323     ///        param_ty
1324     /// ```
1325     ///
1326     /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1327     /// considered `Sized` unless there is an explicit `?Sized` bound.  This would be true in the
1328     /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1329     ///
1330     /// `span` should be the declaration size of the parameter.
1331     pub fn compute_bounds(
1332         &self,
1333         param_ty: Ty<'tcx>,
1334         ast_bounds: &[hir::GenericBound<'_>],
1335         sized_by_default: SizedByDefault,
1336         span: Span,
1337     ) -> Bounds<'tcx> {
1338         let mut bounds = Bounds::default();
1339
1340         self.add_bounds(param_ty, ast_bounds, &mut bounds);
1341         bounds.trait_bounds.sort_by_key(|(t, _, _)| t.def_id());
1342
1343         bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1344             if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
1345         } else {
1346             None
1347         };
1348
1349         bounds
1350     }
1351
1352     /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1353     /// onto `bounds`.
1354     ///
1355     /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1356     /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1357     /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1358     fn add_predicates_for_ast_type_binding(
1359         &self,
1360         hir_ref_id: hir::HirId,
1361         trait_ref: ty::PolyTraitRef<'tcx>,
1362         binding: &ConvertedBinding<'_, 'tcx>,
1363         bounds: &mut Bounds<'tcx>,
1364         speculative: bool,
1365         dup_bindings: &mut FxHashMap<DefId, Span>,
1366         path_span: Span,
1367     ) -> Result<(), ErrorReported> {
1368         let tcx = self.tcx();
1369
1370         if !speculative {
1371             // Given something like `U: SomeTrait<T = X>`, we want to produce a
1372             // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1373             // subtle in the event that `T` is defined in a supertrait of
1374             // `SomeTrait`, because in that case we need to upcast.
1375             //
1376             // That is, consider this case:
1377             //
1378             // ```
1379             // trait SubTrait: SuperTrait<int> { }
1380             // trait SuperTrait<A> { type T; }
1381             //
1382             // ... B: SubTrait<T = foo> ...
1383             // ```
1384             //
1385             // We want to produce `<B as SuperTrait<int>>::T == foo`.
1386
1387             // Find any late-bound regions declared in `ty` that are not
1388             // declared in the trait-ref. These are not well-formed.
1389             //
1390             // Example:
1391             //
1392             //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1393             //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1394             if let ConvertedBindingKind::Equality(ty) = binding.kind {
1395                 let late_bound_in_trait_ref =
1396                     tcx.collect_constrained_late_bound_regions(&trait_ref);
1397                 let late_bound_in_ty =
1398                     tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1399                 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1400                 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1401                 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1402                     let br_name = match *br {
1403                         ty::BrNamed(_, name) => name,
1404                         _ => {
1405                             span_bug!(
1406                                 binding.span,
1407                                 "anonymous bound region {:?} in binding but not trait ref",
1408                                 br
1409                             );
1410                         }
1411                     };
1412                     // FIXME: point at the type params that don't have appropriate lifetimes:
1413                     // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1414                     //                         ----  ----     ^^^^^^^
1415                     struct_span_err!(
1416                         tcx.sess,
1417                         binding.span,
1418                         E0582,
1419                         "binding for associated type `{}` references lifetime `{}`, \
1420                          which does not appear in the trait input types",
1421                         binding.item_name,
1422                         br_name
1423                     )
1424                     .emit();
1425                 }
1426             }
1427         }
1428
1429         let candidate =
1430             if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1431                 // Simple case: X is defined in the current trait.
1432                 trait_ref
1433             } else {
1434                 // Otherwise, we have to walk through the supertraits to find
1435                 // those that do.
1436                 self.one_bound_for_assoc_type(
1437                     || traits::supertraits(tcx, trait_ref),
1438                     || trait_ref.print_only_trait_path().to_string(),
1439                     binding.item_name,
1440                     path_span,
1441                     || match binding.kind {
1442                         ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1443                         _ => None,
1444                     },
1445                 )?
1446             };
1447
1448         let (assoc_ident, def_scope) =
1449             tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1450
1451         // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1452         // of calling `filter_by_name_and_kind`.
1453         let assoc_ty = tcx
1454             .associated_items(candidate.def_id())
1455             .filter_by_name_unhygienic(assoc_ident.name)
1456             .find(|i| {
1457                 i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident
1458             })
1459             .expect("missing associated type");
1460
1461         if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1462             tcx.sess
1463                 .struct_span_err(
1464                     binding.span,
1465                     &format!("associated type `{}` is private", binding.item_name),
1466                 )
1467                 .span_label(binding.span, "private associated type")
1468                 .emit();
1469         }
1470         tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1471
1472         if !speculative {
1473             dup_bindings
1474                 .entry(assoc_ty.def_id)
1475                 .and_modify(|prev_span| {
1476                     struct_span_err!(
1477                         self.tcx().sess,
1478                         binding.span,
1479                         E0719,
1480                         "the value of the associated type `{}` (from trait `{}`) \
1481                          is already specified",
1482                         binding.item_name,
1483                         tcx.def_path_str(assoc_ty.container.id())
1484                     )
1485                     .span_label(binding.span, "re-bound here")
1486                     .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1487                     .emit();
1488                 })
1489                 .or_insert(binding.span);
1490         }
1491
1492         match binding.kind {
1493             ConvertedBindingKind::Equality(ref ty) => {
1494                 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1495                 // the "projection predicate" for:
1496                 //
1497                 // `<T as Iterator>::Item = u32`
1498                 bounds.projection_bounds.push((
1499                     candidate.map_bound(|trait_ref| ty::ProjectionPredicate {
1500                         projection_ty: ty::ProjectionTy::from_ref_and_name(
1501                             tcx,
1502                             trait_ref,
1503                             binding.item_name,
1504                         ),
1505                         ty,
1506                     }),
1507                     binding.span,
1508                 ));
1509             }
1510             ConvertedBindingKind::Constraint(ast_bounds) => {
1511                 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1512                 //
1513                 // `<T as Iterator>::Item: Debug`
1514                 //
1515                 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1516                 // parameter to have a skipped binder.
1517                 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1518                 self.add_bounds(param_ty, ast_bounds, bounds);
1519             }
1520         }
1521         Ok(())
1522     }
1523
1524     fn ast_path_to_ty(
1525         &self,
1526         span: Span,
1527         did: DefId,
1528         item_segment: &hir::PathSegment<'_>,
1529     ) -> Ty<'tcx> {
1530         let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1531         self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1532     }
1533
1534     fn conv_object_ty_poly_trait_ref(
1535         &self,
1536         span: Span,
1537         trait_bounds: &[hir::PolyTraitRef<'_>],
1538         lifetime: &hir::Lifetime,
1539     ) -> Ty<'tcx> {
1540         let tcx = self.tcx();
1541
1542         let mut bounds = Bounds::default();
1543         let mut potential_assoc_types = Vec::new();
1544         let dummy_self = self.tcx().types.trait_object_dummy_self;
1545         for trait_bound in trait_bounds.iter().rev() {
1546             if let GenericArgCountResult {
1547                 correct:
1548                     Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1549                 ..
1550             } = self.instantiate_poly_trait_ref(
1551                 trait_bound,
1552                 Constness::NotConst,
1553                 dummy_self,
1554                 &mut bounds,
1555             ) {
1556                 potential_assoc_types.extend(cur_potential_assoc_types.into_iter());
1557             }
1558         }
1559
1560         // Expand trait aliases recursively and check that only one regular (non-auto) trait
1561         // is used and no 'maybe' bounds are used.
1562         let expanded_traits =
1563             traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1564         let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1565             expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1566         if regular_traits.len() > 1 {
1567             let first_trait = &regular_traits[0];
1568             let additional_trait = &regular_traits[1];
1569             let mut err = struct_span_err!(
1570                 tcx.sess,
1571                 additional_trait.bottom().1,
1572                 E0225,
1573                 "only auto traits can be used as additional traits in a trait object"
1574             );
1575             additional_trait.label_with_exp_info(
1576                 &mut err,
1577                 "additional non-auto trait",
1578                 "additional use",
1579             );
1580             first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1581             err.emit();
1582         }
1583
1584         if regular_traits.is_empty() && auto_traits.is_empty() {
1585             struct_span_err!(
1586                 tcx.sess,
1587                 span,
1588                 E0224,
1589                 "at least one trait is required for an object type"
1590             )
1591             .emit();
1592             return tcx.types.err;
1593         }
1594
1595         // Check that there are no gross object safety violations;
1596         // most importantly, that the supertraits don't contain `Self`,
1597         // to avoid ICEs.
1598         for item in &regular_traits {
1599             let object_safety_violations =
1600                 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1601             if !object_safety_violations.is_empty() {
1602                 report_object_safety_error(
1603                     tcx,
1604                     span,
1605                     item.trait_ref().def_id(),
1606                     &object_safety_violations[..],
1607                 )
1608                 .emit();
1609                 return tcx.types.err;
1610             }
1611         }
1612
1613         // Use a `BTreeSet` to keep output in a more consistent order.
1614         let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1615
1616         let regular_traits_refs_spans = bounds
1617             .trait_bounds
1618             .into_iter()
1619             .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1620
1621         for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1622             assert_eq!(constness, Constness::NotConst);
1623
1624             for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1625                 debug!(
1626                     "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1627                     obligation.predicate
1628                 );
1629                 match obligation.predicate.kind() {
1630                     ty::PredicateKind::Trait(pred, _) => {
1631                         associated_types.entry(span).or_default().extend(
1632                             tcx.associated_items(pred.def_id())
1633                                 .in_definition_order()
1634                                 .filter(|item| item.kind == ty::AssocKind::Type)
1635                                 .map(|item| item.def_id),
1636                         );
1637                     }
1638                     &ty::PredicateKind::Projection(pred) => {
1639                         // A `Self` within the original bound will be substituted with a
1640                         // `trait_object_dummy_self`, so check for that.
1641                         let references_self =
1642                             pred.skip_binder().ty.walk().any(|arg| arg == dummy_self.into());
1643
1644                         // If the projection output contains `Self`, force the user to
1645                         // elaborate it explicitly to avoid a lot of complexity.
1646                         //
1647                         // The "classicaly useful" case is the following:
1648                         // ```
1649                         //     trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1650                         //         type MyOutput;
1651                         //     }
1652                         // ```
1653                         //
1654                         // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1655                         // but actually supporting that would "expand" to an infinitely-long type
1656                         // `fix $ Ï„ â†’ dyn MyTrait<MyOutput = X, Output = <Ï„ as MyTrait>::MyOutput`.
1657                         //
1658                         // Instead, we force the user to write
1659                         // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1660                         // the discussion in #56288 for alternatives.
1661                         if !references_self {
1662                             // Include projections defined on supertraits.
1663                             bounds.projection_bounds.push((pred, span));
1664                         }
1665                     }
1666                     _ => (),
1667                 }
1668             }
1669         }
1670
1671         for (projection_bound, _) in &bounds.projection_bounds {
1672             for def_ids in associated_types.values_mut() {
1673                 def_ids.remove(&projection_bound.projection_def_id());
1674             }
1675         }
1676
1677         self.complain_about_missing_associated_types(
1678             associated_types,
1679             potential_assoc_types,
1680             trait_bounds,
1681         );
1682
1683         // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1684         // `dyn Trait + Send`.
1685         auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1686         auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1687         debug!("regular_traits: {:?}", regular_traits);
1688         debug!("auto_traits: {:?}", auto_traits);
1689
1690         // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1691         // removing the dummy `Self` type (`trait_object_dummy_self`).
1692         let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1693             if trait_ref.self_ty() != dummy_self {
1694                 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1695                 // which picks up non-supertraits where clauses - but also, the object safety
1696                 // completely ignores trait aliases, which could be object safety hazards. We
1697                 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1698                 // disabled. (#66420)
1699                 tcx.sess.delay_span_bug(
1700                     DUMMY_SP,
1701                     &format!(
1702                         "trait_ref_to_existential called on {:?} with non-dummy Self",
1703                         trait_ref,
1704                     ),
1705                 );
1706             }
1707             ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1708         };
1709
1710         // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1711         let existential_trait_refs =
1712             regular_traits.iter().map(|i| i.trait_ref().map_bound(trait_ref_to_existential));
1713         let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1714             bound.map_bound(|b| {
1715                 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1716                 ty::ExistentialProjection {
1717                     ty: b.ty,
1718                     item_def_id: b.projection_ty.item_def_id,
1719                     substs: trait_ref.substs,
1720                 }
1721             })
1722         });
1723
1724         // Calling `skip_binder` is okay because the predicates are re-bound.
1725         let regular_trait_predicates = existential_trait_refs
1726             .map(|trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1727         let auto_trait_predicates = auto_traits
1728             .into_iter()
1729             .map(|trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1730         let mut v = regular_trait_predicates
1731             .chain(auto_trait_predicates)
1732             .chain(
1733                 existential_projections
1734                     .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())),
1735             )
1736             .collect::<SmallVec<[_; 8]>>();
1737         v.sort_by(|a, b| a.stable_cmp(tcx, b));
1738         v.dedup();
1739         let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1740
1741         // Use explicitly-specified region bound.
1742         let region_bound = if !lifetime.is_elided() {
1743             self.ast_region_to_region(lifetime, None)
1744         } else {
1745             self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1746                 if tcx.named_region(lifetime.hir_id).is_some() {
1747                     self.ast_region_to_region(lifetime, None)
1748                 } else {
1749                     self.re_infer(None, span).unwrap_or_else(|| {
1750                         // FIXME: these can be redundant with E0106, but not always.
1751                         struct_span_err!(
1752                             tcx.sess,
1753                             span,
1754                             E0228,
1755                             "the lifetime bound for this object type cannot be deduced \
1756                              from context; please supply an explicit bound"
1757                         )
1758                         .emit();
1759                         tcx.lifetimes.re_static
1760                     })
1761                 }
1762             })
1763         };
1764         debug!("region_bound: {:?}", region_bound);
1765
1766         let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1767         debug!("trait_object_type: {:?}", ty);
1768         ty
1769     }
1770
1771     /// When there are any missing associated types, emit an E0191 error and attempt to supply a
1772     /// reasonable suggestion on how to write it. For the case of multiple associated types in the
1773     /// same trait bound have the same name (as they come from different super-traits), we instead
1774     /// emit a generic note suggesting using a `where` clause to constraint instead.
1775     fn complain_about_missing_associated_types(
1776         &self,
1777         associated_types: FxHashMap<Span, BTreeSet<DefId>>,
1778         potential_assoc_types: Vec<Span>,
1779         trait_bounds: &[hir::PolyTraitRef<'_>],
1780     ) {
1781         if associated_types.values().all(|v| v.is_empty()) {
1782             return;
1783         }
1784         let tcx = self.tcx();
1785         // FIXME: Marked `mut` so that we can replace the spans further below with a more
1786         // appropriate one, but this should be handled earlier in the span assignment.
1787         let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
1788             .into_iter()
1789             .map(|(span, def_ids)| {
1790                 (span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
1791             })
1792             .collect();
1793         let mut names = vec![];
1794
1795         // Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
1796         // `issue-22560.rs`.
1797         let mut trait_bound_spans: Vec<Span> = vec![];
1798         for (span, items) in &associated_types {
1799             if !items.is_empty() {
1800                 trait_bound_spans.push(*span);
1801             }
1802             for assoc_item in items {
1803                 let trait_def_id = assoc_item.container.id();
1804                 names.push(format!(
1805                     "`{}` (from trait `{}`)",
1806                     assoc_item.ident,
1807                     tcx.def_path_str(trait_def_id),
1808                 ));
1809             }
1810         }
1811         if let ([], [bound]) = (&potential_assoc_types[..], &trait_bounds) {
1812             match &bound.trait_ref.path.segments[..] {
1813                 // FIXME: `trait_ref.path.span` can point to a full path with multiple
1814                 // segments, even though `trait_ref.path.segments` is of length `1`. Work
1815                 // around that bug here, even though it should be fixed elsewhere.
1816                 // This would otherwise cause an invalid suggestion. For an example, look at
1817                 // `src/test/ui/issues/issue-28344.rs` where instead of the following:
1818                 //
1819                 //   error[E0191]: the value of the associated type `Output`
1820                 //                 (from trait `std::ops::BitXor`) must be specified
1821                 //   --> $DIR/issue-28344.rs:4:17
1822                 //    |
1823                 // LL |     let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1824                 //    |                 ^^^^^^ help: specify the associated type:
1825                 //    |                              `BitXor<Output = Type>`
1826                 //
1827                 // we would output:
1828                 //
1829                 //   error[E0191]: the value of the associated type `Output`
1830                 //                 (from trait `std::ops::BitXor`) must be specified
1831                 //   --> $DIR/issue-28344.rs:4:17
1832                 //    |
1833                 // LL |     let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1834                 //    |                 ^^^^^^^^^^^^^ help: specify the associated type:
1835                 //    |                                     `BitXor::bitor<Output = Type>`
1836                 [segment] if segment.args.is_none() => {
1837                     trait_bound_spans = vec![segment.ident.span];
1838                     associated_types = associated_types
1839                         .into_iter()
1840                         .map(|(_, items)| (segment.ident.span, items))
1841                         .collect();
1842                 }
1843                 _ => {}
1844             }
1845         }
1846         names.sort();
1847         trait_bound_spans.sort();
1848         let mut err = struct_span_err!(
1849             tcx.sess,
1850             trait_bound_spans,
1851             E0191,
1852             "the value of the associated type{} {} must be specified",
1853             pluralize!(names.len()),
1854             names.join(", "),
1855         );
1856         let mut suggestions = vec![];
1857         let mut types_count = 0;
1858         let mut where_constraints = vec![];
1859         for (span, assoc_items) in &associated_types {
1860             let mut names: FxHashMap<_, usize> = FxHashMap::default();
1861             for item in assoc_items {
1862                 types_count += 1;
1863                 *names.entry(item.ident.name).or_insert(0) += 1;
1864             }
1865             let mut dupes = false;
1866             for item in assoc_items {
1867                 let prefix = if names[&item.ident.name] > 1 {
1868                     let trait_def_id = item.container.id();
1869                     dupes = true;
1870                     format!("{}::", tcx.def_path_str(trait_def_id))
1871                 } else {
1872                     String::new()
1873                 };
1874                 if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
1875                     err.span_label(sp, format!("`{}{}` defined here", prefix, item.ident));
1876                 }
1877             }
1878             if potential_assoc_types.len() == assoc_items.len() {
1879                 // Only suggest when the amount of missing associated types equals the number of
1880                 // extra type arguments present, as that gives us a relatively high confidence
1881                 // that the user forgot to give the associtated type's name. The canonical
1882                 // example would be trying to use `Iterator<isize>` instead of
1883                 // `Iterator<Item = isize>`.
1884                 for (potential, item) in potential_assoc_types.iter().zip(assoc_items.iter()) {
1885                     if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*potential) {
1886                         suggestions.push((*potential, format!("{} = {}", item.ident, snippet)));
1887                     }
1888                 }
1889             } else if let (Ok(snippet), false) =
1890                 (tcx.sess.source_map().span_to_snippet(*span), dupes)
1891             {
1892                 let types: Vec<_> =
1893                     assoc_items.iter().map(|item| format!("{} = Type", item.ident)).collect();
1894                 let code = if snippet.ends_with('>') {
1895                     // The user wrote `Trait<'a>` or similar and we don't have a type we can
1896                     // suggest, but at least we can clue them to the correct syntax
1897                     // `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
1898                     // suggestion.
1899                     format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
1900                 } else {
1901                     // The user wrote `Iterator`, so we don't have a type we can suggest, but at
1902                     // least we can clue them to the correct syntax `Iterator<Item = Type>`.
1903                     format!("{}<{}>", snippet, types.join(", "))
1904                 };
1905                 suggestions.push((*span, code));
1906             } else if dupes {
1907                 where_constraints.push(*span);
1908             }
1909         }
1910         let where_msg = "consider introducing a new type parameter, adding `where` constraints \
1911                          using the fully-qualified path to the associated types";
1912         if !where_constraints.is_empty() && suggestions.is_empty() {
1913             // If there are duplicates associated type names and a single trait bound do not
1914             // use structured suggestion, it means that there are multiple super-traits with
1915             // the same associated type name.
1916             err.help(where_msg);
1917         }
1918         if suggestions.len() != 1 {
1919             // We don't need this label if there's an inline suggestion, show otherwise.
1920             for (span, assoc_items) in &associated_types {
1921                 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1922                 for item in assoc_items {
1923                     types_count += 1;
1924                     *names.entry(item.ident.name).or_insert(0) += 1;
1925                 }
1926                 let mut label = vec![];
1927                 for item in assoc_items {
1928                     let postfix = if names[&item.ident.name] > 1 {
1929                         let trait_def_id = item.container.id();
1930                         format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
1931                     } else {
1932                         String::new()
1933                     };
1934                     label.push(format!("`{}`{}", item.ident, postfix));
1935                 }
1936                 if !label.is_empty() {
1937                     err.span_label(
1938                         *span,
1939                         format!(
1940                             "associated type{} {} must be specified",
1941                             pluralize!(label.len()),
1942                             label.join(", "),
1943                         ),
1944                     );
1945                 }
1946             }
1947         }
1948         if !suggestions.is_empty() {
1949             err.multipart_suggestion(
1950                 &format!("specify the associated type{}", pluralize!(types_count)),
1951                 suggestions,
1952                 Applicability::HasPlaceholders,
1953             );
1954             if !where_constraints.is_empty() {
1955                 err.span_help(where_constraints, where_msg);
1956             }
1957         }
1958         err.emit();
1959     }
1960
1961     fn report_ambiguous_associated_type(
1962         &self,
1963         span: Span,
1964         type_str: &str,
1965         trait_str: &str,
1966         name: Symbol,
1967     ) {
1968         let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1969         if let (Some(_), Ok(snippet)) = (
1970             self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1971             self.tcx().sess.source_map().span_to_snippet(span),
1972         ) {
1973             err.span_suggestion(
1974                 span,
1975                 "you are looking for the module in `std`, not the primitive type",
1976                 format!("std::{}", snippet),
1977                 Applicability::MachineApplicable,
1978             );
1979         } else {
1980             err.span_suggestion(
1981                 span,
1982                 "use fully-qualified syntax",
1983                 format!("<{} as {}>::{}", type_str, trait_str, name),
1984                 Applicability::HasPlaceholders,
1985             );
1986         }
1987         err.emit();
1988     }
1989
1990     // Search for a bound on a type parameter which includes the associated item
1991     // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1992     // This function will fail if there are no suitable bounds or there is
1993     // any ambiguity.
1994     fn find_bound_for_assoc_item(
1995         &self,
1996         ty_param_def_id: LocalDefId,
1997         assoc_name: Ident,
1998         span: Span,
1999     ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
2000         let tcx = self.tcx();
2001
2002         debug!(
2003             "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
2004             ty_param_def_id, assoc_name, span,
2005         );
2006
2007         let predicates =
2008             &self.get_type_parameter_bounds(span, ty_param_def_id.to_def_id()).predicates;
2009
2010         debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
2011
2012         let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id);
2013         let param_name = tcx.hir().ty_param_name(param_hir_id);
2014         self.one_bound_for_assoc_type(
2015             || {
2016                 traits::transitive_bounds(
2017                     tcx,
2018                     predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()),
2019                 )
2020             },
2021             || param_name.to_string(),
2022             assoc_name,
2023             span,
2024             || None,
2025         )
2026     }
2027
2028     // Checks that `bounds` contains exactly one element and reports appropriate
2029     // errors otherwise.
2030     fn one_bound_for_assoc_type<I>(
2031         &self,
2032         all_candidates: impl Fn() -> I,
2033         ty_param_name: impl Fn() -> String,
2034         assoc_name: Ident,
2035         span: Span,
2036         is_equality: impl Fn() -> Option<String>,
2037     ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
2038     where
2039         I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2040     {
2041         let mut matching_candidates = all_candidates()
2042             .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
2043
2044         let bound = match matching_candidates.next() {
2045             Some(bound) => bound,
2046             None => {
2047                 self.complain_about_assoc_type_not_found(
2048                     all_candidates,
2049                     &ty_param_name(),
2050                     assoc_name,
2051                     span,
2052                 );
2053                 return Err(ErrorReported);
2054             }
2055         };
2056
2057         debug!("one_bound_for_assoc_type: bound = {:?}", bound);
2058
2059         if let Some(bound2) = matching_candidates.next() {
2060             debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
2061
2062             let is_equality = is_equality();
2063             let bounds = iter::once(bound).chain(iter::once(bound2)).chain(matching_candidates);
2064             let mut err = if is_equality.is_some() {
2065                 // More specific Error Index entry.
2066                 struct_span_err!(
2067                     self.tcx().sess,
2068                     span,
2069                     E0222,
2070                     "ambiguous associated type `{}` in bounds of `{}`",
2071                     assoc_name,
2072                     ty_param_name()
2073                 )
2074             } else {
2075                 struct_span_err!(
2076                     self.tcx().sess,
2077                     span,
2078                     E0221,
2079                     "ambiguous associated type `{}` in bounds of `{}`",
2080                     assoc_name,
2081                     ty_param_name()
2082                 )
2083             };
2084             err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
2085
2086             let mut where_bounds = vec![];
2087             for bound in bounds {
2088                 let bound_id = bound.def_id();
2089                 let bound_span = self
2090                     .tcx()
2091                     .associated_items(bound_id)
2092                     .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
2093                     .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
2094
2095                 if let Some(bound_span) = bound_span {
2096                     err.span_label(
2097                         bound_span,
2098                         format!(
2099                             "ambiguous `{}` from `{}`",
2100                             assoc_name,
2101                             bound.print_only_trait_path(),
2102                         ),
2103                     );
2104                     if let Some(constraint) = &is_equality {
2105                         where_bounds.push(format!(
2106                             "        T: {trait}::{assoc} = {constraint}",
2107                             trait=bound.print_only_trait_path(),
2108                             assoc=assoc_name,
2109                             constraint=constraint,
2110                         ));
2111                     } else {
2112                         err.span_suggestion(
2113                             span,
2114                             "use fully qualified syntax to disambiguate",
2115                             format!(
2116                                 "<{} as {}>::{}",
2117                                 ty_param_name(),
2118                                 bound.print_only_trait_path(),
2119                                 assoc_name,
2120                             ),
2121                             Applicability::MaybeIncorrect,
2122                         );
2123                     }
2124                 } else {
2125                     err.note(&format!(
2126                         "associated type `{}` could derive from `{}`",
2127                         ty_param_name(),
2128                         bound.print_only_trait_path(),
2129                     ));
2130                 }
2131             }
2132             if !where_bounds.is_empty() {
2133                 err.help(&format!(
2134                     "consider introducing a new type parameter `T` and adding `where` constraints:\
2135                      \n    where\n        T: {},\n{}",
2136                     ty_param_name(),
2137                     where_bounds.join(",\n"),
2138                 ));
2139             }
2140             err.emit();
2141             if !where_bounds.is_empty() {
2142                 return Err(ErrorReported);
2143             }
2144         }
2145         Ok(bound)
2146     }
2147
2148     fn complain_about_assoc_type_not_found<I>(
2149         &self,
2150         all_candidates: impl Fn() -> I,
2151         ty_param_name: &str,
2152         assoc_name: Ident,
2153         span: Span,
2154     ) where
2155         I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2156     {
2157         // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
2158         // valid span, so we point at the whole path segment instead.
2159         let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
2160         let mut err = struct_span_err!(
2161             self.tcx().sess,
2162             span,
2163             E0220,
2164             "associated type `{}` not found for `{}`",
2165             assoc_name,
2166             ty_param_name
2167         );
2168
2169         let all_candidate_names: Vec<_> = all_candidates()
2170             .map(|r| self.tcx().associated_items(r.def_id()).in_definition_order())
2171             .flatten()
2172             .filter_map(
2173                 |item| if item.kind == ty::AssocKind::Type { Some(item.ident.name) } else { None },
2174             )
2175             .collect();
2176
2177         if let (Some(suggested_name), true) = (
2178             find_best_match_for_name(all_candidate_names.iter(), &assoc_name.as_str(), None),
2179             assoc_name.span != DUMMY_SP,
2180         ) {
2181             err.span_suggestion(
2182                 assoc_name.span,
2183                 "there is an associated type with a similar name",
2184                 suggested_name.to_string(),
2185                 Applicability::MaybeIncorrect,
2186             );
2187         } else {
2188             err.span_label(span, format!("associated type `{}` not found", assoc_name));
2189         }
2190
2191         err.emit();
2192     }
2193
2194     // Create a type from a path to an associated type.
2195     // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
2196     // and item_segment is the path segment for `D`. We return a type and a def for
2197     // the whole path.
2198     // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
2199     // parameter or `Self`.
2200     pub fn associated_path_to_ty(
2201         &self,
2202         hir_ref_id: hir::HirId,
2203         span: Span,
2204         qself_ty: Ty<'tcx>,
2205         qself_res: Res,
2206         assoc_segment: &hir::PathSegment<'_>,
2207         permit_variants: bool,
2208     ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
2209         let tcx = self.tcx();
2210         let assoc_ident = assoc_segment.ident;
2211
2212         debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
2213
2214         // Check if we have an enum variant.
2215         let mut variant_resolution = None;
2216         if let ty::Adt(adt_def, _) = qself_ty.kind {
2217             if adt_def.is_enum() {
2218                 let variant_def = adt_def
2219                     .variants
2220                     .iter()
2221                     .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
2222                 if let Some(variant_def) = variant_def {
2223                     if permit_variants {
2224                         tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
2225                         self.prohibit_generics(slice::from_ref(assoc_segment));
2226                         return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
2227                     } else {
2228                         variant_resolution = Some(variant_def.def_id);
2229                     }
2230                 }
2231             }
2232         }
2233
2234         // Find the type of the associated item, and the trait where the associated
2235         // item is declared.
2236         let bound = match (&qself_ty.kind, qself_res) {
2237             (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
2238                 // `Self` in an impl of a trait -- we have a concrete self type and a
2239                 // trait reference.
2240                 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
2241                     Some(trait_ref) => trait_ref,
2242                     None => {
2243                         // A cycle error occurred, most likely.
2244                         return Err(ErrorReported);
2245                     }
2246                 };
2247
2248                 self.one_bound_for_assoc_type(
2249                     || traits::supertraits(tcx, ty::Binder::bind(trait_ref)),
2250                     || "Self".to_string(),
2251                     assoc_ident,
2252                     span,
2253                     || None,
2254                 )?
2255             }
2256             (
2257                 &ty::Param(_),
2258                 Res::SelfTy(Some(param_did), None) | Res::Def(DefKind::TyParam, param_did),
2259             ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
2260             _ => {
2261                 if variant_resolution.is_some() {
2262                     // Variant in type position
2263                     let msg = format!("expected type, found variant `{}`", assoc_ident);
2264                     tcx.sess.span_err(span, &msg);
2265                 } else if qself_ty.is_enum() {
2266                     let mut err = struct_span_err!(
2267                         tcx.sess,
2268                         assoc_ident.span,
2269                         E0599,
2270                         "no variant named `{}` found for enum `{}`",
2271                         assoc_ident,
2272                         qself_ty,
2273                     );
2274
2275                     let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2276                     if let Some(suggested_name) = find_best_match_for_name(
2277                         adt_def.variants.iter().map(|variant| &variant.ident.name),
2278                         &assoc_ident.as_str(),
2279                         None,
2280                     ) {
2281                         err.span_suggestion(
2282                             assoc_ident.span,
2283                             "there is a variant with a similar name",
2284                             suggested_name.to_string(),
2285                             Applicability::MaybeIncorrect,
2286                         );
2287                     } else {
2288                         err.span_label(
2289                             assoc_ident.span,
2290                             format!("variant not found in `{}`", qself_ty),
2291                         );
2292                     }
2293
2294                     if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
2295                         let sp = tcx.sess.source_map().guess_head_span(sp);
2296                         err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2297                     }
2298
2299                     err.emit();
2300                 } else if !qself_ty.references_error() {
2301                     // Don't print `TyErr` to the user.
2302                     self.report_ambiguous_associated_type(
2303                         span,
2304                         &qself_ty.to_string(),
2305                         "Trait",
2306                         assoc_ident.name,
2307                     );
2308                 }
2309                 return Err(ErrorReported);
2310             }
2311         };
2312
2313         let trait_did = bound.def_id();
2314         let (assoc_ident, def_scope) =
2315             tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
2316
2317         // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
2318         // of calling `filter_by_name_and_kind`.
2319         let item = tcx
2320             .associated_items(trait_did)
2321             .in_definition_order()
2322             .find(|i| {
2323                 i.kind.namespace() == Namespace::TypeNS
2324                     && i.ident.normalize_to_macros_2_0() == assoc_ident
2325             })
2326             .expect("missing associated type");
2327
2328         let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
2329         let ty = self.normalize_ty(span, ty);
2330
2331         let kind = DefKind::AssocTy;
2332         if !item.vis.is_accessible_from(def_scope, tcx) {
2333             let kind = kind.descr(item.def_id);
2334             let msg = format!("{} `{}` is private", kind, assoc_ident);
2335             tcx.sess
2336                 .struct_span_err(span, &msg)
2337                 .span_label(span, &format!("private {}", kind))
2338                 .emit();
2339         }
2340         tcx.check_stability(item.def_id, Some(hir_ref_id), span);
2341
2342         if let Some(variant_def_id) = variant_resolution {
2343             tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
2344                 let mut err = lint.build("ambiguous associated item");
2345                 let mut could_refer_to = |kind: DefKind, def_id, also| {
2346                     let note_msg = format!(
2347                         "`{}` could{} refer to the {} defined here",
2348                         assoc_ident,
2349                         also,
2350                         kind.descr(def_id)
2351                     );
2352                     err.span_note(tcx.def_span(def_id), &note_msg);
2353                 };
2354
2355                 could_refer_to(DefKind::Variant, variant_def_id, "");
2356                 could_refer_to(kind, item.def_id, " also");
2357
2358                 err.span_suggestion(
2359                     span,
2360                     "use fully-qualified syntax",
2361                     format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2362                     Applicability::MachineApplicable,
2363                 );
2364
2365                 err.emit();
2366             });
2367         }
2368         Ok((ty, kind, item.def_id))
2369     }
2370
2371     fn qpath_to_ty(
2372         &self,
2373         span: Span,
2374         opt_self_ty: Option<Ty<'tcx>>,
2375         item_def_id: DefId,
2376         trait_segment: &hir::PathSegment<'_>,
2377         item_segment: &hir::PathSegment<'_>,
2378     ) -> Ty<'tcx> {
2379         let tcx = self.tcx();
2380
2381         let trait_def_id = tcx.parent(item_def_id).unwrap();
2382
2383         debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2384
2385         let self_ty = if let Some(ty) = opt_self_ty {
2386             ty
2387         } else {
2388             let path_str = tcx.def_path_str(trait_def_id);
2389
2390             let def_id = self.item_def_id();
2391
2392             debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2393
2394             let parent_def_id = def_id
2395                 .and_then(|def_id| {
2396                     def_id.as_local().map(|def_id| tcx.hir().as_local_hir_id(def_id))
2397                 })
2398                 .map(|hir_id| tcx.hir().get_parent_did(hir_id).to_def_id());
2399
2400             debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2401
2402             // If the trait in segment is the same as the trait defining the item,
2403             // use the `<Self as ..>` syntax in the error.
2404             let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
2405             let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2406
2407             let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2408                 "Self"
2409             } else {
2410                 "Type"
2411             };
2412
2413             self.report_ambiguous_associated_type(
2414                 span,
2415                 type_name,
2416                 &path_str,
2417                 item_segment.ident.name,
2418             );
2419             return tcx.types.err;
2420         };
2421
2422         debug!("qpath_to_ty: self_type={:?}", self_ty);
2423
2424         let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
2425
2426         let item_substs = self.create_substs_for_associated_item(
2427             tcx,
2428             span,
2429             item_def_id,
2430             item_segment,
2431             trait_ref.substs,
2432         );
2433
2434         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2435
2436         self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2437     }
2438
2439     pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2440         &self,
2441         segments: T,
2442     ) -> bool {
2443         let mut has_err = false;
2444         for segment in segments {
2445             let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2446             for arg in segment.generic_args().args {
2447                 let (span, kind) = match arg {
2448                     hir::GenericArg::Lifetime(lt) => {
2449                         if err_for_lt {
2450                             continue;
2451                         }
2452                         err_for_lt = true;
2453                         has_err = true;
2454                         (lt.span, "lifetime")
2455                     }
2456                     hir::GenericArg::Type(ty) => {
2457                         if err_for_ty {
2458                             continue;
2459                         }
2460                         err_for_ty = true;
2461                         has_err = true;
2462                         (ty.span, "type")
2463                     }
2464                     hir::GenericArg::Const(ct) => {
2465                         if err_for_ct {
2466                             continue;
2467                         }
2468                         err_for_ct = true;
2469                         has_err = true;
2470                         (ct.span, "const")
2471                     }
2472                 };
2473                 let mut err = struct_span_err!(
2474                     self.tcx().sess,
2475                     span,
2476                     E0109,
2477                     "{} arguments are not allowed for this type",
2478                     kind,
2479                 );
2480                 err.span_label(span, format!("{} argument not allowed", kind));
2481                 err.emit();
2482                 if err_for_lt && err_for_ty && err_for_ct {
2483                     break;
2484                 }
2485             }
2486
2487             // Only emit the first error to avoid overloading the user with error messages.
2488             if let [binding, ..] = segment.generic_args().bindings {
2489                 has_err = true;
2490                 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2491             }
2492         }
2493         has_err
2494     }
2495
2496     pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
2497         let mut err = struct_span_err!(
2498             tcx.sess,
2499             span,
2500             E0229,
2501             "associated type bindings are not allowed here"
2502         );
2503         err.span_label(span, "associated type not allowed here").emit();
2504     }
2505
2506     /// Prohibits explicit lifetime arguments if late-bound lifetime parameters
2507     /// are present. This is used both for datatypes and function calls.
2508     fn prohibit_explicit_late_bound_lifetimes(
2509         tcx: TyCtxt<'_>,
2510         def: &ty::Generics,
2511         args: &hir::GenericArgs<'_>,
2512         position: GenericArgPosition,
2513     ) -> ExplicitLateBound {
2514         let param_counts = def.own_counts();
2515         let arg_counts = args.own_counts();
2516         let infer_lifetimes = position != GenericArgPosition::Type && arg_counts.lifetimes == 0;
2517
2518         if infer_lifetimes {
2519             ExplicitLateBound::No
2520         } else if let Some(span_late) = def.has_late_bound_regions {
2521             let msg = "cannot specify lifetime arguments explicitly \
2522                        if late bound lifetime parameters are present";
2523             let note = "the late bound lifetime parameter is introduced here";
2524             let span = args.args[0].span();
2525             if position == GenericArgPosition::Value
2526                 && arg_counts.lifetimes != param_counts.lifetimes
2527             {
2528                 let mut err = tcx.sess.struct_span_err(span, msg);
2529                 err.span_note(span_late, note);
2530                 err.emit();
2531             } else {
2532                 let mut multispan = MultiSpan::from_span(span);
2533                 multispan.push_span_label(span_late, note.to_string());
2534                 tcx.struct_span_lint_hir(
2535                     LATE_BOUND_LIFETIME_ARGUMENTS,
2536                     args.args[0].id(),
2537                     multispan,
2538                     |lint| lint.build(msg).emit(),
2539                 );
2540             }
2541             ExplicitLateBound::Yes
2542         } else {
2543             ExplicitLateBound::No
2544         }
2545     }
2546
2547     // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2548     pub fn def_ids_for_value_path_segments(
2549         &self,
2550         segments: &[hir::PathSegment<'_>],
2551         self_ty: Option<Ty<'tcx>>,
2552         kind: DefKind,
2553         def_id: DefId,
2554     ) -> Vec<PathSeg> {
2555         // We need to extract the type parameters supplied by the user in
2556         // the path `path`. Due to the current setup, this is a bit of a
2557         // tricky-process; the problem is that resolve only tells us the
2558         // end-point of the path resolution, and not the intermediate steps.
2559         // Luckily, we can (at least for now) deduce the intermediate steps
2560         // just from the end-point.
2561         //
2562         // There are basically five cases to consider:
2563         //
2564         // 1. Reference to a constructor of a struct:
2565         //
2566         //        struct Foo<T>(...)
2567         //
2568         //    In this case, the parameters are declared in the type space.
2569         //
2570         // 2. Reference to a constructor of an enum variant:
2571         //
2572         //        enum E<T> { Foo(...) }
2573         //
2574         //    In this case, the parameters are defined in the type space,
2575         //    but may be specified either on the type or the variant.
2576         //
2577         // 3. Reference to a fn item or a free constant:
2578         //
2579         //        fn foo<T>() { }
2580         //
2581         //    In this case, the path will again always have the form
2582         //    `a::b::foo::<T>` where only the final segment should have
2583         //    type parameters. However, in this case, those parameters are
2584         //    declared on a value, and hence are in the `FnSpace`.
2585         //
2586         // 4. Reference to a method or an associated constant:
2587         //
2588         //        impl<A> SomeStruct<A> {
2589         //            fn foo<B>(...)
2590         //        }
2591         //
2592         //    Here we can have a path like
2593         //    `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2594         //    may appear in two places. The penultimate segment,
2595         //    `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2596         //    final segment, `foo::<B>` contains parameters in fn space.
2597         //
2598         // The first step then is to categorize the segments appropriately.
2599
2600         let tcx = self.tcx();
2601
2602         assert!(!segments.is_empty());
2603         let last = segments.len() - 1;
2604
2605         let mut path_segs = vec![];
2606
2607         match kind {
2608             // Case 1. Reference to a struct constructor.
2609             DefKind::Ctor(CtorOf::Struct, ..) => {
2610                 // Everything but the final segment should have no
2611                 // parameters at all.
2612                 let generics = tcx.generics_of(def_id);
2613                 // Variant and struct constructors use the
2614                 // generics of their parent type definition.
2615                 let generics_def_id = generics.parent.unwrap_or(def_id);
2616                 path_segs.push(PathSeg(generics_def_id, last));
2617             }
2618
2619             // Case 2. Reference to a variant constructor.
2620             DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2621                 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2622                 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2623                     debug_assert!(adt_def.is_enum());
2624                     (adt_def.did, last)
2625                 } else if last >= 1 && segments[last - 1].args.is_some() {
2626                     // Everything but the penultimate segment should have no
2627                     // parameters at all.
2628                     let mut def_id = def_id;
2629
2630                     // `DefKind::Ctor` -> `DefKind::Variant`
2631                     if let DefKind::Ctor(..) = kind {
2632                         def_id = tcx.parent(def_id).unwrap()
2633                     }
2634
2635                     // `DefKind::Variant` -> `DefKind::Enum`
2636                     let enum_def_id = tcx.parent(def_id).unwrap();
2637                     (enum_def_id, last - 1)
2638                 } else {
2639                     // FIXME: lint here recommending `Enum::<...>::Variant` form
2640                     // instead of `Enum::Variant::<...>` form.
2641
2642                     // Everything but the final segment should have no
2643                     // parameters at all.
2644                     let generics = tcx.generics_of(def_id);
2645                     // Variant and struct constructors use the
2646                     // generics of their parent type definition.
2647                     (generics.parent.unwrap_or(def_id), last)
2648                 };
2649                 path_segs.push(PathSeg(generics_def_id, index));
2650             }
2651
2652             // Case 3. Reference to a top-level value.
2653             DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2654                 path_segs.push(PathSeg(def_id, last));
2655             }
2656
2657             // Case 4. Reference to a method or associated const.
2658             DefKind::AssocFn | DefKind::AssocConst => {
2659                 if segments.len() >= 2 {
2660                     let generics = tcx.generics_of(def_id);
2661                     path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2662                 }
2663                 path_segs.push(PathSeg(def_id, last));
2664             }
2665
2666             kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2667         }
2668
2669         debug!("path_segs = {:?}", path_segs);
2670
2671         path_segs
2672     }
2673
2674     // Check a type `Path` and convert it to a `Ty`.
2675     pub fn res_to_ty(
2676         &self,
2677         opt_self_ty: Option<Ty<'tcx>>,
2678         path: &hir::Path<'_>,
2679         permit_variants: bool,
2680     ) -> Ty<'tcx> {
2681         let tcx = self.tcx();
2682
2683         debug!(
2684             "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2685             path.res, opt_self_ty, path.segments
2686         );
2687
2688         let span = path.span;
2689         match path.res {
2690             Res::Def(DefKind::OpaqueTy, did) => {
2691                 // Check for desugared `impl Trait`.
2692                 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2693                 let item_segment = path.segments.split_last().unwrap();
2694                 self.prohibit_generics(item_segment.1);
2695                 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2696                 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2697             }
2698             Res::Def(
2699                 DefKind::Enum
2700                 | DefKind::TyAlias
2701                 | DefKind::Struct
2702                 | DefKind::Union
2703                 | DefKind::ForeignTy,
2704                 did,
2705             ) => {
2706                 assert_eq!(opt_self_ty, None);
2707                 self.prohibit_generics(path.segments.split_last().unwrap().1);
2708                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2709             }
2710             Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2711                 // Convert "variant type" as if it were a real type.
2712                 // The resulting `Ty` is type of the variant's enum for now.
2713                 assert_eq!(opt_self_ty, None);
2714
2715                 let path_segs =
2716                     self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2717                 let generic_segs: FxHashSet<_> =
2718                     path_segs.iter().map(|PathSeg(_, index)| index).collect();
2719                 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2720                     |(index, seg)| {
2721                         if !generic_segs.contains(&index) { Some(seg) } else { None }
2722                     },
2723                 ));
2724
2725                 let PathSeg(def_id, index) = path_segs.last().unwrap();
2726                 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2727             }
2728             Res::Def(DefKind::TyParam, def_id) => {
2729                 assert_eq!(opt_self_ty, None);
2730                 self.prohibit_generics(path.segments);
2731
2732                 let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
2733                 let item_id = tcx.hir().get_parent_node(hir_id);
2734                 let item_def_id = tcx.hir().local_def_id(item_id);
2735                 let generics = tcx.generics_of(item_def_id);
2736                 let index = generics.param_def_id_to_index[&def_id];
2737                 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2738             }
2739             Res::SelfTy(Some(_), None) => {
2740                 // `Self` in trait or type alias.
2741                 assert_eq!(opt_self_ty, None);
2742                 self.prohibit_generics(path.segments);
2743                 tcx.types.self_param
2744             }
2745             Res::SelfTy(_, Some(def_id)) => {
2746                 // `Self` in impl (we know the concrete type).
2747                 assert_eq!(opt_self_ty, None);
2748                 self.prohibit_generics(path.segments);
2749                 // Try to evaluate any array length constants.
2750                 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2751             }
2752             Res::Def(DefKind::AssocTy, def_id) => {
2753                 debug_assert!(path.segments.len() >= 2);
2754                 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2755                 self.qpath_to_ty(
2756                     span,
2757                     opt_self_ty,
2758                     def_id,
2759                     &path.segments[path.segments.len() - 2],
2760                     path.segments.last().unwrap(),
2761                 )
2762             }
2763             Res::PrimTy(prim_ty) => {
2764                 assert_eq!(opt_self_ty, None);
2765                 self.prohibit_generics(path.segments);
2766                 match prim_ty {
2767                     hir::PrimTy::Bool => tcx.types.bool,
2768                     hir::PrimTy::Char => tcx.types.char,
2769                     hir::PrimTy::Int(it) => tcx.mk_mach_int(it),
2770                     hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(uit),
2771                     hir::PrimTy::Float(ft) => tcx.mk_mach_float(ft),
2772                     hir::PrimTy::Str => tcx.mk_str(),
2773                 }
2774             }
2775             Res::Err => {
2776                 self.set_tainted_by_errors();
2777                 self.tcx().types.err
2778             }
2779             _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2780         }
2781     }
2782
2783     /// Parses the programmer's textual representation of a type into our
2784     /// internal notion of a type.
2785     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2786         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind);
2787
2788         let tcx = self.tcx();
2789
2790         let result_ty = match ast_ty.kind {
2791             hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2792             hir::TyKind::Ptr(ref mt) => {
2793                 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2794             }
2795             hir::TyKind::Rptr(ref region, ref mt) => {
2796                 let r = self.ast_region_to_region(region, None);
2797                 debug!("ast_ty_to_ty: r={:?}", r);
2798                 let t = self.ast_ty_to_ty(&mt.ty);
2799                 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2800             }
2801             hir::TyKind::Never => tcx.types.never,
2802             hir::TyKind::Tup(ref fields) => {
2803                 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2804             }
2805             hir::TyKind::BareFn(ref bf) => {
2806                 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2807                 tcx.mk_fn_ptr(self.ty_of_fn(
2808                     bf.unsafety,
2809                     bf.abi,
2810                     &bf.decl,
2811                     &hir::Generics::empty(),
2812                     None,
2813                 ))
2814             }
2815             hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2816                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2817             }
2818             hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2819                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2820                 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2821                 self.res_to_ty(opt_self_ty, path, false)
2822             }
2823             hir::TyKind::Def(item_id, ref lifetimes) => {
2824                 let did = tcx.hir().local_def_id(item_id.id);
2825                 self.impl_trait_ty_to_ty(did.to_def_id(), lifetimes)
2826             }
2827             hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2828                 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2829                 let ty = self.ast_ty_to_ty(qself);
2830
2831                 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2832                     path.res
2833                 } else {
2834                     Res::Err
2835                 };
2836                 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2837                     .map(|(ty, _, _)| ty)
2838                     .unwrap_or(tcx.types.err)
2839             }
2840             hir::TyKind::Array(ref ty, ref length) => {
2841                 let length_def_id = tcx.hir().local_def_id(length.hir_id);
2842                 let length = ty::Const::from_anon_const(tcx, length_def_id);
2843                 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2844                 self.normalize_ty(ast_ty.span, array_ty)
2845             }
2846             hir::TyKind::Typeof(ref _e) => {
2847                 struct_span_err!(
2848                     tcx.sess,
2849                     ast_ty.span,
2850                     E0516,
2851                     "`typeof` is a reserved keyword but unimplemented"
2852                 )
2853                 .span_label(ast_ty.span, "reserved keyword")
2854                 .emit();
2855
2856                 tcx.types.err
2857             }
2858             hir::TyKind::Infer => {
2859                 // Infer also appears as the type of arguments or return
2860                 // values in a ExprKind::Closure, or as
2861                 // the type of local variables. Both of these cases are
2862                 // handled specially and will not descend into this routine.
2863                 self.ty_infer(None, ast_ty.span)
2864             }
2865             hir::TyKind::Err => tcx.types.err,
2866         };
2867
2868         debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2869
2870         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2871         result_ty
2872     }
2873
2874     pub fn impl_trait_ty_to_ty(
2875         &self,
2876         def_id: DefId,
2877         lifetimes: &[hir::GenericArg<'_>],
2878     ) -> Ty<'tcx> {
2879         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2880         let tcx = self.tcx();
2881
2882         let generics = tcx.generics_of(def_id);
2883
2884         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2885         let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2886             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2887                 // Our own parameters are the resolved lifetimes.
2888                 match param.kind {
2889                     GenericParamDefKind::Lifetime => {
2890                         if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2891                             self.ast_region_to_region(lifetime, None).into()
2892                         } else {
2893                             bug!()
2894                         }
2895                     }
2896                     _ => bug!(),
2897                 }
2898             } else {
2899                 // Replace all parent lifetimes with `'static`.
2900                 match param.kind {
2901                     GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
2902                     _ => tcx.mk_param_from_def(param),
2903                 }
2904             }
2905         });
2906         debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2907
2908         let ty = tcx.mk_opaque(def_id, substs);
2909         debug!("impl_trait_ty_to_ty: {}", ty);
2910         ty
2911     }
2912
2913     pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2914         match ty.kind {
2915             hir::TyKind::Infer if expected_ty.is_some() => {
2916                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2917                 expected_ty.unwrap()
2918             }
2919             _ => self.ast_ty_to_ty(ty),
2920         }
2921     }
2922
2923     pub fn ty_of_fn(
2924         &self,
2925         unsafety: hir::Unsafety,
2926         abi: abi::Abi,
2927         decl: &hir::FnDecl<'_>,
2928         generics: &hir::Generics<'_>,
2929         ident_span: Option<Span>,
2930     ) -> ty::PolyFnSig<'tcx> {
2931         debug!("ty_of_fn");
2932
2933         let tcx = self.tcx();
2934
2935         // We proactively collect all the inferred type params to emit a single error per fn def.
2936         let mut visitor = PlaceholderHirTyCollector::default();
2937         for ty in decl.inputs {
2938             visitor.visit_ty(ty);
2939         }
2940         walk_generics(&mut visitor, generics);
2941
2942         let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2943         let output_ty = match decl.output {
2944             hir::FnRetTy::Return(ref output) => {
2945                 visitor.visit_ty(output);
2946                 self.ast_ty_to_ty(output)
2947             }
2948             hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2949         };
2950
2951         debug!("ty_of_fn: output_ty={:?}", output_ty);
2952
2953         let bare_fn_ty =
2954             ty::Binder::bind(tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi));
2955
2956         if let (false, Some(ident_span)) = (self.allow_ty_infer(), ident_span) {
2957             // We always collect the spans for placeholder types when evaluating `fn`s, but we
2958             // only want to emit an error complaining about them if infer types (`_`) are not
2959             // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2960             // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2961             crate::collect::placeholder_type_error(
2962                 tcx,
2963                 ident_span.shrink_to_hi(),
2964                 &generics.params[..],
2965                 visitor.0,
2966                 true,
2967             );
2968         }
2969
2970         // Find any late-bound regions declared in return type that do
2971         // not appear in the arguments. These are not well-formed.
2972         //
2973         // Example:
2974         //     for<'a> fn() -> &'a str <-- 'a is bad
2975         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2976         let inputs = bare_fn_ty.inputs();
2977         let late_bound_in_args =
2978             tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2979         let output = bare_fn_ty.output();
2980         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2981         for br in late_bound_in_ret.difference(&late_bound_in_args) {
2982             let lifetime_name = match *br {
2983                 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2984                 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2985             };
2986             let mut err = struct_span_err!(
2987                 tcx.sess,
2988                 decl.output.span(),
2989                 E0581,
2990                 "return type references {} which is not constrained by the fn input types",
2991                 lifetime_name
2992             );
2993             if let ty::BrAnon(_) = *br {
2994                 // The only way for an anonymous lifetime to wind up
2995                 // in the return type but **also** be unconstrained is
2996                 // if it only appears in "associated types" in the
2997                 // input. See #47511 for an example. In this case,
2998                 // though we can easily give a hint that ought to be
2999                 // relevant.
3000                 err.note(
3001                     "lifetimes appearing in an associated type are not considered constrained",
3002                 );
3003             }
3004             err.emit();
3005         }
3006
3007         bare_fn_ty
3008     }
3009
3010     /// Given the bounds on an object, determines what single region bound (if any) we can
3011     /// use to summarize this type. The basic idea is that we will use the bound the user
3012     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
3013     /// for region bounds. It may be that we can derive no bound at all, in which case
3014     /// we return `None`.
3015     fn compute_object_lifetime_bound(
3016         &self,
3017         span: Span,
3018         existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
3019     ) -> Option<ty::Region<'tcx>> // if None, use the default
3020     {
3021         let tcx = self.tcx();
3022
3023         debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
3024
3025         // No explicit region bound specified. Therefore, examine trait
3026         // bounds and see if we can derive region bounds from those.
3027         let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3028
3029         // If there are no derived region bounds, then report back that we
3030         // can find no region bound. The caller will use the default.
3031         if derived_region_bounds.is_empty() {
3032             return None;
3033         }
3034
3035         // If any of the derived region bounds are 'static, that is always
3036         // the best choice.
3037         if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
3038             return Some(tcx.lifetimes.re_static);
3039         }
3040
3041         // Determine whether there is exactly one unique region in the set
3042         // of derived region bounds. If so, use that. Otherwise, report an
3043         // error.
3044         let r = derived_region_bounds[0];
3045         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3046             struct_span_err!(
3047                 tcx.sess,
3048                 span,
3049                 E0227,
3050                 "ambiguous lifetime bound, explicit lifetime bound required"
3051             )
3052             .emit();
3053         }
3054         Some(r)
3055     }
3056 }
3057
3058 /// Collects together a list of bounds that are applied to some type,
3059 /// after they've been converted into `ty` form (from the HIR
3060 /// representations). These lists of bounds occur in many places in
3061 /// Rust's syntax:
3062 ///
3063 /// ```text
3064 /// trait Foo: Bar + Baz { }
3065 ///            ^^^^^^^^^ supertrait list bounding the `Self` type parameter
3066 ///
3067 /// fn foo<T: Bar + Baz>() { }
3068 ///           ^^^^^^^^^ bounding the type parameter `T`
3069 ///
3070 /// impl dyn Bar + Baz
3071 ///          ^^^^^^^^^ bounding the forgotten dynamic type
3072 /// ```
3073 ///
3074 /// Our representation is a bit mixed here -- in some cases, we
3075 /// include the self type (e.g., `trait_bounds`) but in others we do
3076 #[derive(Default, PartialEq, Eq, Clone, Debug)]
3077 pub struct Bounds<'tcx> {
3078     /// A list of region bounds on the (implicit) self type. So if you
3079     /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
3080     /// the `T` is not explicitly included).
3081     pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
3082
3083     /// A list of trait bounds. So if you had `T: Debug` this would be
3084     /// `T: Debug`. Note that the self-type is explicit here.
3085     pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span, Constness)>,
3086
3087     /// A list of projection equality bounds. So if you had `T:
3088     /// Iterator<Item = u32>` this would include `<T as
3089     /// Iterator>::Item => u32`. Note that the self-type is explicit
3090     /// here.
3091     pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
3092
3093     /// `Some` if there is *no* `?Sized` predicate. The `span`
3094     /// is the location in the source of the `T` declaration which can
3095     /// be cited as the source of the `T: Sized` requirement.
3096     pub implicitly_sized: Option<Span>,
3097 }
3098
3099 impl<'tcx> Bounds<'tcx> {
3100     /// Converts a bounds list into a flat set of predicates (like
3101     /// where-clauses). Because some of our bounds listings (e.g.,
3102     /// regions) don't include the self-type, you must supply the
3103     /// self-type here (the `param_ty` parameter).
3104     pub fn predicates(
3105         &self,
3106         tcx: TyCtxt<'tcx>,
3107         param_ty: Ty<'tcx>,
3108     ) -> Vec<(ty::Predicate<'tcx>, Span)> {
3109         // If it could be sized, and is, add the `Sized` predicate.
3110         let sized_predicate = self.implicitly_sized.and_then(|span| {
3111             tcx.lang_items().sized_trait().map(|sized| {
3112                 let trait_ref = ty::Binder::bind(ty::TraitRef {
3113                     def_id: sized,
3114                     substs: tcx.mk_substs_trait(param_ty, &[]),
3115                 });
3116                 (trait_ref.without_const().to_predicate(tcx), span)
3117             })
3118         });
3119
3120         sized_predicate
3121             .into_iter()
3122             .chain(
3123                 self.region_bounds
3124                     .iter()
3125                     .map(|&(region_bound, span)| {
3126                         // Account for the binder being introduced below; no need to shift `param_ty`
3127                         // because, at present at least, it either only refers to early-bound regions,
3128                         // or it's a generic associated type that deliberately has escaping bound vars.
3129                         let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
3130                         let outlives = ty::OutlivesPredicate(param_ty, region_bound);
3131                         (ty::Binder::bind(outlives).to_predicate(tcx), span)
3132                     })
3133                     .chain(self.trait_bounds.iter().map(|&(bound_trait_ref, span, constness)| {
3134                         let predicate = bound_trait_ref.with_constness(constness).to_predicate(tcx);
3135                         (predicate, span)
3136                     }))
3137                     .chain(
3138                         self.projection_bounds
3139                             .iter()
3140                             .map(|&(projection, span)| (projection.to_predicate(tcx), span)),
3141                     ),
3142             )
3143             .collect()
3144     }
3145 }