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