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