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