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