]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/astconv.rs
Rollup merge of #70038 - DutchGhost:const-forget-tests, r=RalfJung
[rust.git] / src / librustc_typeck / astconv.rs
1 // ignore-tidy-filelength FIXME(#67418) Split up this file.
2 //! Conversion from AST representation of types to the `ty.rs` representation.
3 //! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an
4 //! instance of `AstConv`.
5
6 // ignore-tidy-filelength
7
8 use crate::collect::PlaceholderHirTyCollector;
9 use crate::middle::lang_items::SizedTraitLangItem;
10 use crate::middle::resolve_lifetime as rl;
11 use crate::require_c_abi_if_c_variadic;
12 use crate::util::common::ErrorReported;
13 use rustc::ty::subst::{self, InternalSubsts, Subst, SubstsRef};
14 use rustc::ty::{self, Const, DefIdTree, ToPredicate, Ty, TyCtxt, TypeFoldable, WithConstness};
15 use rustc::ty::{GenericParamDef, GenericParamDefKind};
16 use rustc_ast::ast;
17 use rustc_ast::util::lev_distance::find_best_match_for_name;
18 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
19 use rustc_errors::{pluralize, struct_span_err, Applicability, DiagnosticId};
20 use rustc_hir as hir;
21 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
22 use rustc_hir::def_id::DefId;
23 use rustc_hir::intravisit::Visitor;
24 use rustc_hir::print;
25 use rustc_hir::{Constness, ExprKind, GenericArg, GenericArgs};
26 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, LATE_BOUND_LIFETIME_ARGUMENTS};
27 use rustc_session::parse::feature_err;
28 use rustc_session::Session;
29 use rustc_span::symbol::sym;
30 use rustc_span::{MultiSpan, Span, DUMMY_SP};
31 use rustc_target::spec::abi;
32 use rustc_trait_selection::traits;
33 use rustc_trait_selection::traits::astconv_object_safety_violations;
34 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
35 use rustc_trait_selection::traits::wf::object_region_bounds;
36
37 use smallvec::SmallVec;
38 use std::collections::BTreeSet;
39 use std::iter;
40 use std::slice;
41
42 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                         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         mut provided_kind: impl FnMut(&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 constraints 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 mut inferred_params = vec![];
755         let substs = Self::create_substs_for_generic_args(
756             tcx,
757             def_id,
758             parent_substs,
759             self_ty.is_some(),
760             self_ty,
761             arg_count_correct.is_ok(),
762             // Provide the generic args, and whether types should be inferred.
763             |did| {
764                 if did == def_id {
765                     (Some(generic_args), infer_args)
766                 } else {
767                     // The last component of this tuple is unimportant.
768                     (None, false)
769                 }
770             },
771             // Provide substitutions for parameters for which (valid) arguments have been provided.
772             |param, arg| match (&param.kind, arg) {
773                 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
774                     self.ast_region_to_region(&lt, Some(param)).into()
775                 }
776                 (GenericParamDefKind::Type { .. }, GenericArg::Type(ty)) => {
777                     if let (hir::TyKind::Infer, false) = (&ty.kind, self.allow_ty_infer()) {
778                         inferred_params.push(ty.span);
779                         tcx.types.err.into()
780                     } else {
781                         self.ast_ty_to_ty(&ty).into()
782                     }
783                 }
784                 (GenericParamDefKind::Const, GenericArg::Const(ct)) => {
785                     self.ast_const_to_const(&ct.value, tcx.type_of(param.def_id)).into()
786                 }
787                 _ => unreachable!(),
788             },
789             // Provide substitutions for parameters for which arguments are inferred.
790             |substs, param, infer_args| {
791                 match param.kind {
792                     GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
793                     GenericParamDefKind::Type { has_default, .. } => {
794                         if !infer_args && has_default {
795                             // No type parameter provided, but a default exists.
796
797                             // If we are converting an object type, then the
798                             // `Self` parameter is unknown. However, some of the
799                             // other type parameters may reference `Self` in their
800                             // defaults. This will lead to an ICE if we are not
801                             // careful!
802                             if default_needs_object_self(param) {
803                                 missing_type_params.push(param.name.to_string());
804                                 tcx.types.err.into()
805                             } else {
806                                 // This is a default type parameter.
807                                 self.normalize_ty(
808                                     span,
809                                     tcx.at(span).type_of(param.def_id).subst_spanned(
810                                         tcx,
811                                         substs.unwrap(),
812                                         Some(span),
813                                     ),
814                                 )
815                                 .into()
816                             }
817                         } else if infer_args {
818                             // No type parameters were provided, we can infer all.
819                             let param =
820                                 if !default_needs_object_self(param) { Some(param) } else { None };
821                             self.ty_infer(param, span).into()
822                         } else {
823                             // We've already errored above about the mismatch.
824                             tcx.types.err.into()
825                         }
826                     }
827                     GenericParamDefKind::Const => {
828                         // FIXME(const_generics:defaults)
829                         if infer_args {
830                             // No const parameters were provided, we can infer all.
831                             let ty = tcx.at(span).type_of(param.def_id);
832                             self.ct_infer(ty, Some(param), span).into()
833                         } else {
834                             // We've already errored above about the mismatch.
835                             tcx.consts.err.into()
836                         }
837                     }
838                 }
839             },
840         );
841         if !inferred_params.is_empty() {
842             // We always collect the spans for placeholder types when evaluating `fn`s, but we
843             // only want to emit an error complaining about them if infer types (`_`) are not
844             // allowed. `allow_ty_infer` gates this behavior.
845             crate::collect::placeholder_type_error(
846                 tcx,
847                 inferred_params[0],
848                 &[],
849                 inferred_params,
850                 false,
851             );
852         }
853
854         self.complain_about_missing_type_params(
855             missing_type_params,
856             def_id,
857             span,
858             generic_args.args.is_empty(),
859         );
860
861         // Convert associated-type bindings or constraints into a separate vector.
862         // Example: Given this:
863         //
864         //     T: Iterator<Item = u32>
865         //
866         // The `T` is passed in as a self-type; the `Item = u32` is
867         // not a "type parameter" of the `Iterator` trait, but rather
868         // a restriction on `<T as Iterator>::Item`, so it is passed
869         // back separately.
870         let assoc_bindings = generic_args
871             .bindings
872             .iter()
873             .map(|binding| {
874                 let kind = match binding.kind {
875                     hir::TypeBindingKind::Equality { ref ty } => {
876                         ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
877                     }
878                     hir::TypeBindingKind::Constraint { ref bounds } => {
879                         ConvertedBindingKind::Constraint(bounds)
880                     }
881                 };
882                 ConvertedBinding { item_name: binding.ident, kind, span: binding.span }
883             })
884             .collect();
885
886         debug!(
887             "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
888             generic_params, self_ty, substs
889         );
890
891         (substs, assoc_bindings, arg_count_correct)
892     }
893
894     crate fn create_substs_for_associated_item(
895         &self,
896         tcx: TyCtxt<'tcx>,
897         span: Span,
898         item_def_id: DefId,
899         item_segment: &hir::PathSegment<'_>,
900         parent_substs: SubstsRef<'tcx>,
901     ) -> SubstsRef<'tcx> {
902         if tcx.generics_of(item_def_id).params.is_empty() {
903             self.prohibit_generics(slice::from_ref(item_segment));
904
905             parent_substs
906         } else {
907             self.create_substs_for_ast_path(
908                 span,
909                 item_def_id,
910                 parent_substs,
911                 item_segment.generic_args(),
912                 item_segment.infer_args,
913                 None,
914             )
915             .0
916         }
917     }
918
919     /// On missing type parameters, emit an E0393 error and provide a structured suggestion using
920     /// the type parameter's name as a placeholder.
921     fn complain_about_missing_type_params(
922         &self,
923         missing_type_params: Vec<String>,
924         def_id: DefId,
925         span: Span,
926         empty_generic_args: bool,
927     ) {
928         if missing_type_params.is_empty() {
929             return;
930         }
931         let display =
932             missing_type_params.iter().map(|n| format!("`{}`", n)).collect::<Vec<_>>().join(", ");
933         let mut err = struct_span_err!(
934             self.tcx().sess,
935             span,
936             E0393,
937             "the type parameter{} {} must be explicitly specified",
938             pluralize!(missing_type_params.len()),
939             display,
940         );
941         err.span_label(
942             self.tcx().def_span(def_id),
943             &format!(
944                 "type parameter{} {} must be specified for this",
945                 pluralize!(missing_type_params.len()),
946                 display,
947             ),
948         );
949         let mut suggested = false;
950         if let (Ok(snippet), true) = (
951             self.tcx().sess.source_map().span_to_snippet(span),
952             // Don't suggest setting the type params if there are some already: the order is
953             // tricky to get right and the user will already know what the syntax is.
954             empty_generic_args,
955         ) {
956             if snippet.ends_with('>') {
957                 // The user wrote `Trait<'a, T>` or similar. To provide an accurate suggestion
958                 // we would have to preserve the right order. For now, as clearly the user is
959                 // aware of the syntax, we do nothing.
960             } else {
961                 // The user wrote `Iterator`, so we don't have a type we can suggest, but at
962                 // least we can clue them to the correct syntax `Iterator<Type>`.
963                 err.span_suggestion(
964                     span,
965                     &format!(
966                         "set the type parameter{plural} to the desired type{plural}",
967                         plural = pluralize!(missing_type_params.len()),
968                     ),
969                     format!("{}<{}>", snippet, missing_type_params.join(", ")),
970                     Applicability::HasPlaceholders,
971                 );
972                 suggested = true;
973             }
974         }
975         if !suggested {
976             err.span_label(
977                 span,
978                 format!(
979                     "missing reference{} to {}",
980                     pluralize!(missing_type_params.len()),
981                     display,
982                 ),
983             );
984         }
985         err.note(
986             "because of the default `Self` reference, type parameters must be \
987                   specified on object types",
988         );
989         err.emit();
990     }
991
992     /// Instantiates the path for the given trait reference, assuming that it's
993     /// bound to a valid trait type. Returns the `DefId` of the defining trait.
994     /// The type _cannot_ be a type other than a trait type.
995     ///
996     /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
997     /// are disallowed. Otherwise, they are pushed onto the vector given.
998     pub fn instantiate_mono_trait_ref(
999         &self,
1000         trait_ref: &hir::TraitRef<'_>,
1001         self_ty: Ty<'tcx>,
1002     ) -> ty::TraitRef<'tcx> {
1003         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
1004
1005         self.ast_path_to_mono_trait_ref(
1006             trait_ref.path.span,
1007             trait_ref.trait_def_id(),
1008             self_ty,
1009             trait_ref.path.segments.last().unwrap(),
1010         )
1011     }
1012
1013     /// The given trait-ref must actually be a trait.
1014     pub(super) fn instantiate_poly_trait_ref_inner(
1015         &self,
1016         trait_ref: &hir::TraitRef<'_>,
1017         span: Span,
1018         constness: Constness,
1019         self_ty: Ty<'tcx>,
1020         bounds: &mut Bounds<'tcx>,
1021         speculative: bool,
1022     ) -> Result<(), GenericArgCountMismatch> {
1023         let trait_def_id = trait_ref.trait_def_id();
1024
1025         debug!("instantiate_poly_trait_ref({:?}, def_id={:?})", trait_ref, trait_def_id);
1026
1027         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
1028
1029         let path_span = if let [segment] = &trait_ref.path.segments[..] {
1030             // FIXME: `trait_ref.path.span` can point to a full path with multiple
1031             // segments, even though `trait_ref.path.segments` is of length `1`. Work
1032             // around that bug here, even though it should be fixed elsewhere.
1033             // This would otherwise cause an invalid suggestion. For an example, look at
1034             // `src/test/ui/issues/issue-28344.rs`.
1035             segment.ident.span
1036         } else {
1037             trait_ref.path.span
1038         };
1039         let (substs, assoc_bindings, arg_count_correct) = self.create_substs_for_ast_trait_ref(
1040             path_span,
1041             trait_def_id,
1042             self_ty,
1043             trait_ref.path.segments.last().unwrap(),
1044         );
1045         let poly_trait_ref = ty::Binder::bind(ty::TraitRef::new(trait_def_id, substs));
1046
1047         bounds.trait_bounds.push((poly_trait_ref, span, constness));
1048
1049         let mut dup_bindings = FxHashMap::default();
1050         for binding in &assoc_bindings {
1051             // Specify type to assert that error was already reported in `Err` case.
1052             let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
1053                 trait_ref.hir_ref_id,
1054                 poly_trait_ref,
1055                 binding,
1056                 bounds,
1057                 speculative,
1058                 &mut dup_bindings,
1059                 span,
1060             );
1061             // Okay to ignore `Err` because of `ErrorReported` (see above).
1062         }
1063
1064         debug!(
1065             "instantiate_poly_trait_ref({:?}, bounds={:?}) -> {:?}",
1066             trait_ref, bounds, poly_trait_ref
1067         );
1068
1069         arg_count_correct
1070     }
1071
1072     /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
1073     /// a full trait reference. The resulting trait reference is returned. This may also generate
1074     /// auxiliary bounds, which are added to `bounds`.
1075     ///
1076     /// Example:
1077     ///
1078     /// ```
1079     /// poly_trait_ref = Iterator<Item = u32>
1080     /// self_ty = Foo
1081     /// ```
1082     ///
1083     /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
1084     ///
1085     /// **A note on binders:** against our usual convention, there is an implied bounder around
1086     /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
1087     /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
1088     /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
1089     /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
1090     /// however.
1091     pub fn instantiate_poly_trait_ref(
1092         &self,
1093         poly_trait_ref: &hir::PolyTraitRef<'_>,
1094         constness: Constness,
1095         self_ty: Ty<'tcx>,
1096         bounds: &mut Bounds<'tcx>,
1097     ) -> Result<(), GenericArgCountMismatch> {
1098         self.instantiate_poly_trait_ref_inner(
1099             &poly_trait_ref.trait_ref,
1100             poly_trait_ref.span,
1101             constness,
1102             self_ty,
1103             bounds,
1104             false,
1105         )
1106     }
1107
1108     fn ast_path_to_mono_trait_ref(
1109         &self,
1110         span: Span,
1111         trait_def_id: DefId,
1112         self_ty: Ty<'tcx>,
1113         trait_segment: &hir::PathSegment<'_>,
1114     ) -> ty::TraitRef<'tcx> {
1115         let (substs, assoc_bindings, _) =
1116             self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
1117         assoc_bindings.first().map(|b| AstConv::prohibit_assoc_ty_binding(self.tcx(), b.span));
1118         ty::TraitRef::new(trait_def_id, substs)
1119     }
1120
1121     /// When the code is using the `Fn` traits directly, instead of the `Fn(A) -> B` syntax, emit
1122     /// an error and attempt to build a reasonable structured suggestion.
1123     fn complain_about_internal_fn_trait(
1124         &self,
1125         span: Span,
1126         trait_def_id: DefId,
1127         trait_segment: &'a hir::PathSegment<'a>,
1128     ) {
1129         let trait_def = self.tcx().trait_def(trait_def_id);
1130
1131         if !self.tcx().features().unboxed_closures
1132             && trait_segment.generic_args().parenthesized != trait_def.paren_sugar
1133         {
1134             // For now, require that parenthetical notation be used only with `Fn()` etc.
1135             let (msg, sugg) = if trait_def.paren_sugar {
1136                 (
1137                     "the precise format of `Fn`-family traits' type parameters is subject to \
1138                      change",
1139                     Some(format!(
1140                         "{}{} -> {}",
1141                         trait_segment.ident,
1142                         trait_segment
1143                             .args
1144                             .as_ref()
1145                             .and_then(|args| args.args.get(0))
1146                             .and_then(|arg| match arg {
1147                                 hir::GenericArg::Type(ty) => {
1148                                     Some(print::to_string(print::NO_ANN, |s| s.print_type(ty)))
1149                                 }
1150                                 _ => None,
1151                             })
1152                             .unwrap_or_else(|| "()".to_string()),
1153                         trait_segment
1154                             .generic_args()
1155                             .bindings
1156                             .iter()
1157                             .filter_map(|b| match (b.ident.as_str() == "Output", &b.kind) {
1158                                 (true, hir::TypeBindingKind::Equality { ty }) => {
1159                                     Some(print::to_string(print::NO_ANN, |s| s.print_type(ty)))
1160                                 }
1161                                 _ => None,
1162                             })
1163                             .next()
1164                             .unwrap_or_else(|| "()".to_string()),
1165                     )),
1166                 )
1167             } else {
1168                 ("parenthetical notation is only stable when used with `Fn`-family traits", None)
1169             };
1170             let sess = &self.tcx().sess.parse_sess;
1171             let mut err = feature_err(sess, sym::unboxed_closures, span, msg);
1172             if let Some(sugg) = sugg {
1173                 let msg = "use parenthetical notation instead";
1174                 err.span_suggestion(span, msg, sugg, Applicability::MaybeIncorrect);
1175             }
1176             err.emit();
1177         }
1178     }
1179
1180     fn create_substs_for_ast_trait_ref<'a>(
1181         &self,
1182         span: Span,
1183         trait_def_id: DefId,
1184         self_ty: Ty<'tcx>,
1185         trait_segment: &'a hir::PathSegment<'a>,
1186     ) -> (SubstsRef<'tcx>, Vec<ConvertedBinding<'a, 'tcx>>, Result<(), GenericArgCountMismatch>)
1187     {
1188         debug!("create_substs_for_ast_trait_ref(trait_segment={:?})", trait_segment);
1189
1190         self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
1191
1192         self.create_substs_for_ast_path(
1193             span,
1194             trait_def_id,
1195             &[],
1196             trait_segment.generic_args(),
1197             trait_segment.infer_args,
1198             Some(self_ty),
1199         )
1200     }
1201
1202     fn trait_defines_associated_type_named(
1203         &self,
1204         trait_def_id: DefId,
1205         assoc_name: ast::Ident,
1206     ) -> bool {
1207         self.tcx()
1208             .associated_items(trait_def_id)
1209             .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
1210             .is_some()
1211     }
1212
1213     // Returns `true` if a bounds list includes `?Sized`.
1214     pub fn is_unsized(&self, ast_bounds: &[hir::GenericBound<'_>], span: Span) -> bool {
1215         let tcx = self.tcx();
1216
1217         // Try to find an unbound in bounds.
1218         let mut unbound = None;
1219         for ab in ast_bounds {
1220             if let &hir::GenericBound::Trait(ref ptr, hir::TraitBoundModifier::Maybe) = ab {
1221                 if unbound.is_none() {
1222                     unbound = Some(&ptr.trait_ref);
1223                 } else {
1224                     struct_span_err!(
1225                         tcx.sess,
1226                         span,
1227                         E0203,
1228                         "type parameter has more than one relaxed default \
1229                         bound, only one is supported"
1230                     )
1231                     .emit();
1232                 }
1233             }
1234         }
1235
1236         let kind_id = tcx.lang_items().require(SizedTraitLangItem);
1237         match unbound {
1238             Some(tpb) => {
1239                 // FIXME(#8559) currently requires the unbound to be built-in.
1240                 if let Ok(kind_id) = kind_id {
1241                     if tpb.path.res != Res::Def(DefKind::Trait, kind_id) {
1242                         tcx.sess.span_warn(
1243                             span,
1244                             "default bound relaxed for a type parameter, but \
1245                              this does nothing because the given bound is not \
1246                              a default; only `?Sized` is supported",
1247                         );
1248                     }
1249                 }
1250             }
1251             _ if kind_id.is_ok() => {
1252                 return false;
1253             }
1254             // No lang item for `Sized`, so we can't add it as a bound.
1255             None => {}
1256         }
1257
1258         true
1259     }
1260
1261     /// This helper takes a *converted* parameter type (`param_ty`)
1262     /// and an *unconverted* list of bounds:
1263     ///
1264     /// ```
1265     /// fn foo<T: Debug>
1266     ///        ^  ^^^^^ `ast_bounds` parameter, in HIR form
1267     ///        |
1268     ///        `param_ty`, in ty form
1269     /// ```
1270     ///
1271     /// It adds these `ast_bounds` into the `bounds` structure.
1272     ///
1273     /// **A note on binders:** there is an implied binder around
1274     /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
1275     /// for more details.
1276     fn add_bounds(
1277         &self,
1278         param_ty: Ty<'tcx>,
1279         ast_bounds: &[hir::GenericBound<'_>],
1280         bounds: &mut Bounds<'tcx>,
1281     ) {
1282         let mut trait_bounds = Vec::new();
1283         let mut region_bounds = Vec::new();
1284
1285         let constness = self.default_constness_for_trait_bounds();
1286         for ast_bound in ast_bounds {
1287             match *ast_bound {
1288                 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::None) => {
1289                     trait_bounds.push((b, constness))
1290                 }
1291                 hir::GenericBound::Trait(ref b, hir::TraitBoundModifier::MaybeConst) => {
1292                     trait_bounds.push((b, Constness::NotConst))
1293                 }
1294                 hir::GenericBound::Trait(_, hir::TraitBoundModifier::Maybe) => {}
1295                 hir::GenericBound::Outlives(ref l) => region_bounds.push(l),
1296             }
1297         }
1298
1299         for (bound, constness) in trait_bounds {
1300             let _ = self.instantiate_poly_trait_ref(bound, constness, param_ty, bounds);
1301         }
1302
1303         bounds.region_bounds.extend(
1304             region_bounds.into_iter().map(|r| (self.ast_region_to_region(r, None), r.span)),
1305         );
1306     }
1307
1308     /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1309     /// The self-type for the bounds is given by `param_ty`.
1310     ///
1311     /// Example:
1312     ///
1313     /// ```
1314     /// fn foo<T: Bar + Baz>() { }
1315     ///        ^  ^^^^^^^^^ ast_bounds
1316     ///        param_ty
1317     /// ```
1318     ///
1319     /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1320     /// considered `Sized` unless there is an explicit `?Sized` bound.  This would be true in the
1321     /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1322     ///
1323     /// `span` should be the declaration size of the parameter.
1324     pub fn compute_bounds(
1325         &self,
1326         param_ty: Ty<'tcx>,
1327         ast_bounds: &[hir::GenericBound<'_>],
1328         sized_by_default: SizedByDefault,
1329         span: Span,
1330     ) -> Bounds<'tcx> {
1331         let mut bounds = Bounds::default();
1332
1333         self.add_bounds(param_ty, ast_bounds, &mut bounds);
1334         bounds.trait_bounds.sort_by_key(|(t, _, _)| t.def_id());
1335
1336         bounds.implicitly_sized = if let SizedByDefault::Yes = sized_by_default {
1337             if !self.is_unsized(ast_bounds, span) { Some(span) } else { None }
1338         } else {
1339             None
1340         };
1341
1342         bounds
1343     }
1344
1345     /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1346     /// onto `bounds`.
1347     ///
1348     /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1349     /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1350     /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1351     fn add_predicates_for_ast_type_binding(
1352         &self,
1353         hir_ref_id: hir::HirId,
1354         trait_ref: ty::PolyTraitRef<'tcx>,
1355         binding: &ConvertedBinding<'_, 'tcx>,
1356         bounds: &mut Bounds<'tcx>,
1357         speculative: bool,
1358         dup_bindings: &mut FxHashMap<DefId, Span>,
1359         path_span: Span,
1360     ) -> Result<(), ErrorReported> {
1361         let tcx = self.tcx();
1362
1363         if !speculative {
1364             // Given something like `U: SomeTrait<T = X>`, we want to produce a
1365             // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1366             // subtle in the event that `T` is defined in a supertrait of
1367             // `SomeTrait`, because in that case we need to upcast.
1368             //
1369             // That is, consider this case:
1370             //
1371             // ```
1372             // trait SubTrait: SuperTrait<int> { }
1373             // trait SuperTrait<A> { type T; }
1374             //
1375             // ... B: SubTrait<T = foo> ...
1376             // ```
1377             //
1378             // We want to produce `<B as SuperTrait<int>>::T == foo`.
1379
1380             // Find any late-bound regions declared in `ty` that are not
1381             // declared in the trait-ref. These are not well-formed.
1382             //
1383             // Example:
1384             //
1385             //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1386             //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1387             if let ConvertedBindingKind::Equality(ty) = binding.kind {
1388                 let late_bound_in_trait_ref =
1389                     tcx.collect_constrained_late_bound_regions(&trait_ref);
1390                 let late_bound_in_ty =
1391                     tcx.collect_referenced_late_bound_regions(&ty::Binder::bind(ty));
1392                 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1393                 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1394                 for br in late_bound_in_ty.difference(&late_bound_in_trait_ref) {
1395                     let br_name = match *br {
1396                         ty::BrNamed(_, name) => name,
1397                         _ => {
1398                             span_bug!(
1399                                 binding.span,
1400                                 "anonymous bound region {:?} in binding but not trait ref",
1401                                 br
1402                             );
1403                         }
1404                     };
1405                     // FIXME: point at the type params that don't have appropriate lifetimes:
1406                     // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1407                     //                         ----  ----     ^^^^^^^
1408                     struct_span_err!(
1409                         tcx.sess,
1410                         binding.span,
1411                         E0582,
1412                         "binding for associated type `{}` references lifetime `{}`, \
1413                          which does not appear in the trait input types",
1414                         binding.item_name,
1415                         br_name
1416                     )
1417                     .emit();
1418                 }
1419             }
1420         }
1421
1422         let candidate =
1423             if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1424                 // Simple case: X is defined in the current trait.
1425                 trait_ref
1426             } else {
1427                 // Otherwise, we have to walk through the supertraits to find
1428                 // those that do.
1429                 self.one_bound_for_assoc_type(
1430                     || traits::supertraits(tcx, trait_ref),
1431                     || trait_ref.print_only_trait_path().to_string(),
1432                     binding.item_name,
1433                     path_span,
1434                     || match binding.kind {
1435                         ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1436                         _ => None,
1437                     },
1438                 )?
1439             };
1440
1441         let (assoc_ident, def_scope) =
1442             tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1443
1444         // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1445         // of calling `filter_by_name_and_kind`.
1446         let assoc_ty = tcx
1447             .associated_items(candidate.def_id())
1448             .filter_by_name_unhygienic(assoc_ident.name)
1449             .find(|i| {
1450                 i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident
1451             })
1452             .expect("missing associated type");
1453
1454         if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1455             let msg = format!("associated type `{}` is private", binding.item_name);
1456             tcx.sess.span_err(binding.span, &msg);
1457         }
1458         tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span);
1459
1460         if !speculative {
1461             dup_bindings
1462                 .entry(assoc_ty.def_id)
1463                 .and_modify(|prev_span| {
1464                     struct_span_err!(
1465                         self.tcx().sess,
1466                         binding.span,
1467                         E0719,
1468                         "the value of the associated type `{}` (from trait `{}`) \
1469                          is already specified",
1470                         binding.item_name,
1471                         tcx.def_path_str(assoc_ty.container.id())
1472                     )
1473                     .span_label(binding.span, "re-bound here")
1474                     .span_label(*prev_span, format!("`{}` bound here first", binding.item_name))
1475                     .emit();
1476                 })
1477                 .or_insert(binding.span);
1478         }
1479
1480         match binding.kind {
1481             ConvertedBindingKind::Equality(ref ty) => {
1482                 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1483                 // the "projection predicate" for:
1484                 //
1485                 // `<T as Iterator>::Item = u32`
1486                 bounds.projection_bounds.push((
1487                     candidate.map_bound(|trait_ref| ty::ProjectionPredicate {
1488                         projection_ty: ty::ProjectionTy::from_ref_and_name(
1489                             tcx,
1490                             trait_ref,
1491                             binding.item_name,
1492                         ),
1493                         ty,
1494                     }),
1495                     binding.span,
1496                 ));
1497             }
1498             ConvertedBindingKind::Constraint(ast_bounds) => {
1499                 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1500                 //
1501                 // `<T as Iterator>::Item: Debug`
1502                 //
1503                 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1504                 // parameter to have a skipped binder.
1505                 let param_ty = tcx.mk_projection(assoc_ty.def_id, candidate.skip_binder().substs);
1506                 self.add_bounds(param_ty, ast_bounds, bounds);
1507             }
1508         }
1509         Ok(())
1510     }
1511
1512     fn ast_path_to_ty(
1513         &self,
1514         span: Span,
1515         did: DefId,
1516         item_segment: &hir::PathSegment<'_>,
1517     ) -> Ty<'tcx> {
1518         let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1519         self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1520     }
1521
1522     fn conv_object_ty_poly_trait_ref(
1523         &self,
1524         span: Span,
1525         trait_bounds: &[hir::PolyTraitRef<'_>],
1526         lifetime: &hir::Lifetime,
1527     ) -> Ty<'tcx> {
1528         let tcx = self.tcx();
1529
1530         let mut bounds = Bounds::default();
1531         let mut potential_assoc_types = Vec::new();
1532         let dummy_self = self.tcx().types.trait_object_dummy_self;
1533         for trait_bound in trait_bounds.iter().rev() {
1534             if let Err(GenericArgCountMismatch {
1535                 invalid_args: cur_potential_assoc_types, ..
1536             }) = self.instantiate_poly_trait_ref(
1537                 trait_bound,
1538                 Constness::NotConst,
1539                 dummy_self,
1540                 &mut bounds,
1541             ) {
1542                 potential_assoc_types.extend(cur_potential_assoc_types.into_iter());
1543             }
1544         }
1545
1546         // Expand trait aliases recursively and check that only one regular (non-auto) trait
1547         // is used and no 'maybe' bounds are used.
1548         let expanded_traits =
1549             traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1550         let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1551             expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1552         if regular_traits.len() > 1 {
1553             let first_trait = &regular_traits[0];
1554             let additional_trait = &regular_traits[1];
1555             let mut err = struct_span_err!(
1556                 tcx.sess,
1557                 additional_trait.bottom().1,
1558                 E0225,
1559                 "only auto traits can be used as additional traits in a trait object"
1560             );
1561             additional_trait.label_with_exp_info(
1562                 &mut err,
1563                 "additional non-auto trait",
1564                 "additional use",
1565             );
1566             first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1567             err.emit();
1568         }
1569
1570         if regular_traits.is_empty() && auto_traits.is_empty() {
1571             struct_span_err!(
1572                 tcx.sess,
1573                 span,
1574                 E0224,
1575                 "at least one trait is required for an object type"
1576             )
1577             .emit();
1578             return tcx.types.err;
1579         }
1580
1581         // Check that there are no gross object safety violations;
1582         // most importantly, that the supertraits don't contain `Self`,
1583         // to avoid ICEs.
1584         for item in &regular_traits {
1585             let object_safety_violations =
1586                 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1587             if !object_safety_violations.is_empty() {
1588                 report_object_safety_error(
1589                     tcx,
1590                     span,
1591                     item.trait_ref().def_id(),
1592                     object_safety_violations,
1593                 )
1594                 .emit();
1595                 return tcx.types.err;
1596             }
1597         }
1598
1599         // Use a `BTreeSet` to keep output in a more consistent order.
1600         let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1601
1602         let regular_traits_refs_spans = bounds
1603             .trait_bounds
1604             .into_iter()
1605             .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1606
1607         for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1608             assert_eq!(constness, Constness::NotConst);
1609
1610             for trait_ref in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1611                 debug!(
1612                     "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1613                     trait_ref
1614                 );
1615                 match trait_ref {
1616                     ty::Predicate::Trait(pred, _) => {
1617                         associated_types.entry(span).or_default().extend(
1618                             tcx.associated_items(pred.def_id())
1619                                 .in_definition_order()
1620                                 .filter(|item| item.kind == ty::AssocKind::Type)
1621                                 .map(|item| item.def_id),
1622                         );
1623                     }
1624                     ty::Predicate::Projection(pred) => {
1625                         // A `Self` within the original bound will be substituted with a
1626                         // `trait_object_dummy_self`, so check for that.
1627                         let references_self = pred.skip_binder().ty.walk().any(|t| t == dummy_self);
1628
1629                         // If the projection output contains `Self`, force the user to
1630                         // elaborate it explicitly to avoid a lot of complexity.
1631                         //
1632                         // The "classicaly useful" case is the following:
1633                         // ```
1634                         //     trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1635                         //         type MyOutput;
1636                         //     }
1637                         // ```
1638                         //
1639                         // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1640                         // but actually supporting that would "expand" to an infinitely-long type
1641                         // `fix $ Ï„ â†’ dyn MyTrait<MyOutput = X, Output = <Ï„ as MyTrait>::MyOutput`.
1642                         //
1643                         // Instead, we force the user to write
1644                         // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1645                         // the discussion in #56288 for alternatives.
1646                         if !references_self {
1647                             // Include projections defined on supertraits.
1648                             bounds.projection_bounds.push((pred, span));
1649                         }
1650                     }
1651                     _ => (),
1652                 }
1653             }
1654         }
1655
1656         for (projection_bound, _) in &bounds.projection_bounds {
1657             for def_ids in associated_types.values_mut() {
1658                 def_ids.remove(&projection_bound.projection_def_id());
1659             }
1660         }
1661
1662         self.complain_about_missing_associated_types(
1663             associated_types,
1664             potential_assoc_types,
1665             trait_bounds,
1666         );
1667
1668         // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1669         // `dyn Trait + Send`.
1670         auto_traits.sort_by_key(|i| i.trait_ref().def_id());
1671         auto_traits.dedup_by_key(|i| i.trait_ref().def_id());
1672         debug!("regular_traits: {:?}", regular_traits);
1673         debug!("auto_traits: {:?}", auto_traits);
1674
1675         // Transform a `PolyTraitRef` into a `PolyExistentialTraitRef` by
1676         // removing the dummy `Self` type (`trait_object_dummy_self`).
1677         let trait_ref_to_existential = |trait_ref: ty::TraitRef<'tcx>| {
1678             if trait_ref.self_ty() != dummy_self {
1679                 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1680                 // which picks up non-supertraits where clauses - but also, the object safety
1681                 // completely ignores trait aliases, which could be object safety hazards. We
1682                 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1683                 // disabled. (#66420)
1684                 tcx.sess.delay_span_bug(
1685                     DUMMY_SP,
1686                     &format!(
1687                         "trait_ref_to_existential called on {:?} with non-dummy Self",
1688                         trait_ref,
1689                     ),
1690                 );
1691             }
1692             ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1693         };
1694
1695         // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1696         let existential_trait_refs = regular_traits
1697             .iter()
1698             .map(|i| i.trait_ref().map_bound(|trait_ref| trait_ref_to_existential(trait_ref)));
1699         let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1700             bound.map_bound(|b| {
1701                 let trait_ref = trait_ref_to_existential(b.projection_ty.trait_ref(tcx));
1702                 ty::ExistentialProjection {
1703                     ty: b.ty,
1704                     item_def_id: b.projection_ty.item_def_id,
1705                     substs: trait_ref.substs,
1706                 }
1707             })
1708         });
1709
1710         // Calling `skip_binder` is okay because the predicates are re-bound.
1711         let regular_trait_predicates = existential_trait_refs
1712             .map(|trait_ref| ty::ExistentialPredicate::Trait(*trait_ref.skip_binder()));
1713         let auto_trait_predicates = auto_traits
1714             .into_iter()
1715             .map(|trait_ref| ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()));
1716         let mut v = regular_trait_predicates
1717             .chain(auto_trait_predicates)
1718             .chain(
1719                 existential_projections
1720                     .map(|x| ty::ExistentialPredicate::Projection(*x.skip_binder())),
1721             )
1722             .collect::<SmallVec<[_; 8]>>();
1723         v.sort_by(|a, b| a.stable_cmp(tcx, b));
1724         v.dedup();
1725         let existential_predicates = ty::Binder::bind(tcx.mk_existential_predicates(v.into_iter()));
1726
1727         // Use explicitly-specified region bound.
1728         let region_bound = if !lifetime.is_elided() {
1729             self.ast_region_to_region(lifetime, None)
1730         } else {
1731             self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1732                 if tcx.named_region(lifetime.hir_id).is_some() {
1733                     self.ast_region_to_region(lifetime, None)
1734                 } else {
1735                     self.re_infer(None, span).unwrap_or_else(|| {
1736                         struct_span_err!(
1737                             tcx.sess,
1738                             span,
1739                             E0228,
1740                             "the lifetime bound for this object type cannot be deduced \
1741                              from context; please supply an explicit bound"
1742                         )
1743                         .emit();
1744                         tcx.lifetimes.re_static
1745                     })
1746                 }
1747             })
1748         };
1749         debug!("region_bound: {:?}", region_bound);
1750
1751         let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1752         debug!("trait_object_type: {:?}", ty);
1753         ty
1754     }
1755
1756     /// When there are any missing associated types, emit an E0191 error and attempt to supply a
1757     /// reasonable suggestion on how to write it. For the case of multiple associated types in the
1758     /// same trait bound have the same name (as they come from different super-traits), we instead
1759     /// emit a generic note suggesting using a `where` clause to constraint instead.
1760     fn complain_about_missing_associated_types(
1761         &self,
1762         associated_types: FxHashMap<Span, BTreeSet<DefId>>,
1763         potential_assoc_types: Vec<Span>,
1764         trait_bounds: &[hir::PolyTraitRef<'_>],
1765     ) {
1766         if !associated_types.values().any(|v| !v.is_empty()) {
1767             return;
1768         }
1769         let tcx = self.tcx();
1770         // FIXME: Marked `mut` so that we can replace the spans further below with a more
1771         // appropriate one, but this should be handled earlier in the span assignment.
1772         let mut associated_types: FxHashMap<Span, Vec<_>> = associated_types
1773             .into_iter()
1774             .map(|(span, def_ids)| {
1775                 (span, def_ids.into_iter().map(|did| tcx.associated_item(did)).collect())
1776             })
1777             .collect();
1778         let mut names = vec![];
1779
1780         // Account for things like `dyn Foo + 'a`, like in tests `issue-22434.rs` and
1781         // `issue-22560.rs`.
1782         let mut trait_bound_spans: Vec<Span> = vec![];
1783         for (span, items) in &associated_types {
1784             if !items.is_empty() {
1785                 trait_bound_spans.push(*span);
1786             }
1787             for assoc_item in items {
1788                 let trait_def_id = assoc_item.container.id();
1789                 names.push(format!(
1790                     "`{}` (from trait `{}`)",
1791                     assoc_item.ident,
1792                     tcx.def_path_str(trait_def_id),
1793                 ));
1794             }
1795         }
1796
1797         match (&potential_assoc_types[..], &trait_bounds) {
1798             ([], [bound]) => match &bound.trait_ref.path.segments[..] {
1799                 // FIXME: `trait_ref.path.span` can point to a full path with multiple
1800                 // segments, even though `trait_ref.path.segments` is of length `1`. Work
1801                 // around that bug here, even though it should be fixed elsewhere.
1802                 // This would otherwise cause an invalid suggestion. For an example, look at
1803                 // `src/test/ui/issues/issue-28344.rs` where instead of the following:
1804                 //
1805                 //   error[E0191]: the value of the associated type `Output`
1806                 //                 (from trait `std::ops::BitXor`) must be specified
1807                 //   --> $DIR/issue-28344.rs:4:17
1808                 //    |
1809                 // LL |     let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1810                 //    |                 ^^^^^^ help: specify the associated type:
1811                 //    |                              `BitXor<Output = Type>`
1812                 //
1813                 // we would output:
1814                 //
1815                 //   error[E0191]: the value of the associated type `Output`
1816                 //                 (from trait `std::ops::BitXor`) must be specified
1817                 //   --> $DIR/issue-28344.rs:4:17
1818                 //    |
1819                 // LL |     let x: u8 = BitXor::bitor(0 as u8, 0 as u8);
1820                 //    |                 ^^^^^^^^^^^^^ help: specify the associated type:
1821                 //    |                                     `BitXor::bitor<Output = Type>`
1822                 [segment] if segment.args.is_none() => {
1823                     trait_bound_spans = vec![segment.ident.span];
1824                     associated_types = associated_types
1825                         .into_iter()
1826                         .map(|(_, items)| (segment.ident.span, items))
1827                         .collect();
1828                 }
1829                 _ => {}
1830             },
1831             _ => {}
1832         }
1833         names.sort();
1834         trait_bound_spans.sort();
1835         let mut err = struct_span_err!(
1836             tcx.sess,
1837             trait_bound_spans,
1838             E0191,
1839             "the value of the associated type{} {} must be specified",
1840             pluralize!(names.len()),
1841             names.join(", "),
1842         );
1843         let mut suggestions = vec![];
1844         let mut types_count = 0;
1845         let mut where_constraints = vec![];
1846         for (span, assoc_items) in &associated_types {
1847             let mut names: FxHashMap<_, usize> = FxHashMap::default();
1848             for item in assoc_items {
1849                 types_count += 1;
1850                 *names.entry(item.ident.name).or_insert(0) += 1;
1851             }
1852             let mut dupes = false;
1853             for item in assoc_items {
1854                 let prefix = if names[&item.ident.name] > 1 {
1855                     let trait_def_id = item.container.id();
1856                     dupes = true;
1857                     format!("{}::", tcx.def_path_str(trait_def_id))
1858                 } else {
1859                     String::new()
1860                 };
1861                 if let Some(sp) = tcx.hir().span_if_local(item.def_id) {
1862                     err.span_label(sp, format!("`{}{}` defined here", prefix, item.ident));
1863                 }
1864             }
1865             if potential_assoc_types.len() == assoc_items.len() {
1866                 // Only suggest when the amount of missing associated types equals the number of
1867                 // extra type arguments present, as that gives us a relatively high confidence
1868                 // that the user forgot to give the associtated type's name. The canonical
1869                 // example would be trying to use `Iterator<isize>` instead of
1870                 // `Iterator<Item = isize>`.
1871                 for (potential, item) in potential_assoc_types.iter().zip(assoc_items.iter()) {
1872                     if let Ok(snippet) = tcx.sess.source_map().span_to_snippet(*potential) {
1873                         suggestions.push((*potential, format!("{} = {}", item.ident, snippet)));
1874                     }
1875                 }
1876             } else if let (Ok(snippet), false) =
1877                 (tcx.sess.source_map().span_to_snippet(*span), dupes)
1878             {
1879                 let types: Vec<_> =
1880                     assoc_items.iter().map(|item| format!("{} = Type", item.ident)).collect();
1881                 let code = if snippet.ends_with('>') {
1882                     // The user wrote `Trait<'a>` or similar and we don't have a type we can
1883                     // suggest, but at least we can clue them to the correct syntax
1884                     // `Trait<'a, Item = Type>` while accounting for the `<'a>` in the
1885                     // suggestion.
1886                     format!("{}, {}>", &snippet[..snippet.len() - 1], types.join(", "))
1887                 } else {
1888                     // The user wrote `Iterator`, so we don't have a type we can suggest, but at
1889                     // least we can clue them to the correct syntax `Iterator<Item = Type>`.
1890                     format!("{}<{}>", snippet, types.join(", "))
1891                 };
1892                 suggestions.push((*span, code));
1893             } else if dupes {
1894                 where_constraints.push(*span);
1895             }
1896         }
1897         let where_msg = "consider introducing a new type parameter, adding `where` constraints \
1898                          using the fully-qualified path to the associated types";
1899         if !where_constraints.is_empty() && suggestions.is_empty() {
1900             // If there are duplicates associated type names and a single trait bound do not
1901             // use structured suggestion, it means that there are multiple super-traits with
1902             // the same associated type name.
1903             err.help(where_msg);
1904         }
1905         if suggestions.len() != 1 {
1906             // We don't need this label if there's an inline suggestion, show otherwise.
1907             for (span, assoc_items) in &associated_types {
1908                 let mut names: FxHashMap<_, usize> = FxHashMap::default();
1909                 for item in assoc_items {
1910                     types_count += 1;
1911                     *names.entry(item.ident.name).or_insert(0) += 1;
1912                 }
1913                 let mut label = vec![];
1914                 for item in assoc_items {
1915                     let postfix = if names[&item.ident.name] > 1 {
1916                         let trait_def_id = item.container.id();
1917                         format!(" (from trait `{}`)", tcx.def_path_str(trait_def_id))
1918                     } else {
1919                         String::new()
1920                     };
1921                     label.push(format!("`{}`{}", item.ident, postfix));
1922                 }
1923                 if !label.is_empty() {
1924                     err.span_label(
1925                         *span,
1926                         format!(
1927                             "associated type{} {} must be specified",
1928                             pluralize!(label.len()),
1929                             label.join(", "),
1930                         ),
1931                     );
1932                 }
1933             }
1934         }
1935         if !suggestions.is_empty() {
1936             err.multipart_suggestion(
1937                 &format!("specify the associated type{}", pluralize!(types_count)),
1938                 suggestions,
1939                 Applicability::HasPlaceholders,
1940             );
1941             if !where_constraints.is_empty() {
1942                 err.span_help(where_constraints, where_msg);
1943             }
1944         }
1945         err.emit();
1946     }
1947
1948     fn report_ambiguous_associated_type(
1949         &self,
1950         span: Span,
1951         type_str: &str,
1952         trait_str: &str,
1953         name: ast::Name,
1954     ) {
1955         let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1956         if let (Some(_), Ok(snippet)) = (
1957             self.tcx().sess.confused_type_with_std_module.borrow().get(&span),
1958             self.tcx().sess.source_map().span_to_snippet(span),
1959         ) {
1960             err.span_suggestion(
1961                 span,
1962                 "you are looking for the module in `std`, not the primitive type",
1963                 format!("std::{}", snippet),
1964                 Applicability::MachineApplicable,
1965             );
1966         } else {
1967             err.span_suggestion(
1968                 span,
1969                 "use fully-qualified syntax",
1970                 format!("<{} as {}>::{}", type_str, trait_str, name),
1971                 Applicability::HasPlaceholders,
1972             );
1973         }
1974         err.emit();
1975     }
1976
1977     // Search for a bound on a type parameter which includes the associated item
1978     // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1979     // This function will fail if there are no suitable bounds or there is
1980     // any ambiguity.
1981     fn find_bound_for_assoc_item(
1982         &self,
1983         ty_param_def_id: DefId,
1984         assoc_name: ast::Ident,
1985         span: Span,
1986     ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
1987         let tcx = self.tcx();
1988
1989         debug!(
1990             "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1991             ty_param_def_id, assoc_name, span,
1992         );
1993
1994         let predicates = &self.get_type_parameter_bounds(span, ty_param_def_id).predicates;
1995
1996         debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1997
1998         let param_hir_id = tcx.hir().as_local_hir_id(ty_param_def_id).unwrap();
1999         let param_name = tcx.hir().ty_param_name(param_hir_id);
2000         self.one_bound_for_assoc_type(
2001             || {
2002                 traits::transitive_bounds(
2003                     tcx,
2004                     predicates.iter().filter_map(|(p, _)| p.to_opt_poly_trait_ref()),
2005                 )
2006             },
2007             || param_name.to_string(),
2008             assoc_name,
2009             span,
2010             || None,
2011         )
2012     }
2013
2014     // Checks that `bounds` contains exactly one element and reports appropriate
2015     // errors otherwise.
2016     fn one_bound_for_assoc_type<I>(
2017         &self,
2018         all_candidates: impl Fn() -> I,
2019         ty_param_name: impl Fn() -> String,
2020         assoc_name: ast::Ident,
2021         span: Span,
2022         is_equality: impl Fn() -> Option<String>,
2023     ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
2024     where
2025         I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2026     {
2027         let mut matching_candidates = all_candidates()
2028             .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
2029
2030         let bound = match matching_candidates.next() {
2031             Some(bound) => bound,
2032             None => {
2033                 self.complain_about_assoc_type_not_found(
2034                     all_candidates,
2035                     &ty_param_name(),
2036                     assoc_name,
2037                     span,
2038                 );
2039                 return Err(ErrorReported);
2040             }
2041         };
2042
2043         debug!("one_bound_for_assoc_type: bound = {:?}", bound);
2044
2045         if let Some(bound2) = matching_candidates.next() {
2046             debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
2047
2048             let is_equality = is_equality();
2049             let bounds = iter::once(bound).chain(iter::once(bound2)).chain(matching_candidates);
2050             let mut err = if is_equality.is_some() {
2051                 // More specific Error Index entry.
2052                 struct_span_err!(
2053                     self.tcx().sess,
2054                     span,
2055                     E0222,
2056                     "ambiguous associated type `{}` in bounds of `{}`",
2057                     assoc_name,
2058                     ty_param_name()
2059                 )
2060             } else {
2061                 struct_span_err!(
2062                     self.tcx().sess,
2063                     span,
2064                     E0221,
2065                     "ambiguous associated type `{}` in bounds of `{}`",
2066                     assoc_name,
2067                     ty_param_name()
2068                 )
2069             };
2070             err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
2071
2072             let mut where_bounds = vec![];
2073             for bound in bounds {
2074                 let bound_id = bound.def_id();
2075                 let bound_span = self
2076                     .tcx()
2077                     .associated_items(bound_id)
2078                     .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
2079                     .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
2080
2081                 if let Some(bound_span) = bound_span {
2082                     err.span_label(
2083                         bound_span,
2084                         format!(
2085                             "ambiguous `{}` from `{}`",
2086                             assoc_name,
2087                             bound.print_only_trait_path(),
2088                         ),
2089                     );
2090                     if let Some(constraint) = &is_equality {
2091                         where_bounds.push(format!(
2092                             "        T: {trait}::{assoc} = {constraint}",
2093                             trait=bound.print_only_trait_path(),
2094                             assoc=assoc_name,
2095                             constraint=constraint,
2096                         ));
2097                     } else {
2098                         err.span_suggestion(
2099                             span,
2100                             "use fully qualified syntax to disambiguate",
2101                             format!(
2102                                 "<{} as {}>::{}",
2103                                 ty_param_name(),
2104                                 bound.print_only_trait_path(),
2105                                 assoc_name,
2106                             ),
2107                             Applicability::MaybeIncorrect,
2108                         );
2109                     }
2110                 } else {
2111                     err.note(&format!(
2112                         "associated type `{}` could derive from `{}`",
2113                         ty_param_name(),
2114                         bound.print_only_trait_path(),
2115                     ));
2116                 }
2117             }
2118             if !where_bounds.is_empty() {
2119                 err.help(&format!(
2120                     "consider introducing a new type parameter `T` and adding `where` constraints:\
2121                      \n    where\n        T: {},\n{}",
2122                     ty_param_name(),
2123                     where_bounds.join(",\n"),
2124                 ));
2125             }
2126             err.emit();
2127             if !where_bounds.is_empty() {
2128                 return Err(ErrorReported);
2129             }
2130         }
2131         return Ok(bound);
2132     }
2133
2134     fn complain_about_assoc_type_not_found<I>(
2135         &self,
2136         all_candidates: impl Fn() -> I,
2137         ty_param_name: &str,
2138         assoc_name: ast::Ident,
2139         span: Span,
2140     ) where
2141         I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
2142     {
2143         // The fallback span is needed because `assoc_name` might be an `Fn()`'s `Output` without a
2144         // valid span, so we point at the whole path segment instead.
2145         let span = if assoc_name.span != DUMMY_SP { assoc_name.span } else { span };
2146         let mut err = struct_span_err!(
2147             self.tcx().sess,
2148             span,
2149             E0220,
2150             "associated type `{}` not found for `{}`",
2151             assoc_name,
2152             ty_param_name
2153         );
2154
2155         let all_candidate_names: Vec<_> = all_candidates()
2156             .map(|r| self.tcx().associated_items(r.def_id()).in_definition_order())
2157             .flatten()
2158             .filter_map(
2159                 |item| if item.kind == ty::AssocKind::Type { Some(item.ident.name) } else { None },
2160             )
2161             .collect();
2162
2163         if let (Some(suggested_name), true) = (
2164             find_best_match_for_name(all_candidate_names.iter(), &assoc_name.as_str(), None),
2165             assoc_name.span != DUMMY_SP,
2166         ) {
2167             err.span_suggestion(
2168                 assoc_name.span,
2169                 "there is an associated type with a similar name",
2170                 suggested_name.to_string(),
2171                 Applicability::MaybeIncorrect,
2172             );
2173         } else {
2174             err.span_label(span, format!("associated type `{}` not found", assoc_name));
2175         }
2176
2177         err.emit();
2178     }
2179
2180     // Create a type from a path to an associated type.
2181     // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
2182     // and item_segment is the path segment for `D`. We return a type and a def for
2183     // the whole path.
2184     // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
2185     // parameter or `Self`.
2186     pub fn associated_path_to_ty(
2187         &self,
2188         hir_ref_id: hir::HirId,
2189         span: Span,
2190         qself_ty: Ty<'tcx>,
2191         qself_res: Res,
2192         assoc_segment: &hir::PathSegment<'_>,
2193         permit_variants: bool,
2194     ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
2195         let tcx = self.tcx();
2196         let assoc_ident = assoc_segment.ident;
2197
2198         debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
2199
2200         // Check if we have an enum variant.
2201         let mut variant_resolution = None;
2202         if let ty::Adt(adt_def, _) = qself_ty.kind {
2203             if adt_def.is_enum() {
2204                 let variant_def = adt_def
2205                     .variants
2206                     .iter()
2207                     .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
2208                 if let Some(variant_def) = variant_def {
2209                     if permit_variants {
2210                         tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span);
2211                         self.prohibit_generics(slice::from_ref(assoc_segment));
2212                         return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
2213                     } else {
2214                         variant_resolution = Some(variant_def.def_id);
2215                     }
2216                 }
2217             }
2218         }
2219
2220         // Find the type of the associated item, and the trait where the associated
2221         // item is declared.
2222         let bound = match (&qself_ty.kind, qself_res) {
2223             (_, Res::SelfTy(Some(_), Some(impl_def_id))) => {
2224                 // `Self` in an impl of a trait -- we have a concrete self type and a
2225                 // trait reference.
2226                 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
2227                     Some(trait_ref) => trait_ref,
2228                     None => {
2229                         // A cycle error occurred, most likely.
2230                         return Err(ErrorReported);
2231                     }
2232                 };
2233
2234                 self.one_bound_for_assoc_type(
2235                     || traits::supertraits(tcx, ty::Binder::bind(trait_ref)),
2236                     || "Self".to_string(),
2237                     assoc_ident,
2238                     span,
2239                     || None,
2240                 )?
2241             }
2242             (&ty::Param(_), Res::SelfTy(Some(param_did), None))
2243             | (&ty::Param(_), Res::Def(DefKind::TyParam, param_did)) => {
2244                 self.find_bound_for_assoc_item(param_did, assoc_ident, span)?
2245             }
2246             _ => {
2247                 if variant_resolution.is_some() {
2248                     // Variant in type position
2249                     let msg = format!("expected type, found variant `{}`", assoc_ident);
2250                     tcx.sess.span_err(span, &msg);
2251                 } else if qself_ty.is_enum() {
2252                     let mut err = struct_span_err!(
2253                         tcx.sess,
2254                         assoc_ident.span,
2255                         E0599,
2256                         "no variant named `{}` found for enum `{}`",
2257                         assoc_ident,
2258                         qself_ty,
2259                     );
2260
2261                     let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2262                     if let Some(suggested_name) = find_best_match_for_name(
2263                         adt_def.variants.iter().map(|variant| &variant.ident.name),
2264                         &assoc_ident.as_str(),
2265                         None,
2266                     ) {
2267                         err.span_suggestion(
2268                             assoc_ident.span,
2269                             "there is a variant with a similar name",
2270                             suggested_name.to_string(),
2271                             Applicability::MaybeIncorrect,
2272                         );
2273                     } else {
2274                         err.span_label(
2275                             assoc_ident.span,
2276                             format!("variant not found in `{}`", qself_ty),
2277                         );
2278                     }
2279
2280                     if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
2281                         let sp = tcx.sess.source_map().def_span(sp);
2282                         err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2283                     }
2284
2285                     err.emit();
2286                 } else if !qself_ty.references_error() {
2287                     // Don't print `TyErr` to the user.
2288                     self.report_ambiguous_associated_type(
2289                         span,
2290                         &qself_ty.to_string(),
2291                         "Trait",
2292                         assoc_ident.name,
2293                     );
2294                 }
2295                 return Err(ErrorReported);
2296             }
2297         };
2298
2299         let trait_did = bound.def_id();
2300         let (assoc_ident, def_scope) =
2301             tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
2302
2303         // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
2304         // of calling `filter_by_name_and_kind`.
2305         let item = tcx
2306             .associated_items(trait_did)
2307             .in_definition_order()
2308             .find(|i| {
2309                 i.kind.namespace() == Namespace::TypeNS
2310                     && i.ident.normalize_to_macros_2_0() == assoc_ident
2311             })
2312             .expect("missing associated type");
2313
2314         let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
2315         let ty = self.normalize_ty(span, ty);
2316
2317         let kind = DefKind::AssocTy;
2318         if !item.vis.is_accessible_from(def_scope, tcx) {
2319             let msg = format!("{} `{}` is private", kind.descr(item.def_id), assoc_ident);
2320             tcx.sess.span_err(span, &msg);
2321         }
2322         tcx.check_stability(item.def_id, Some(hir_ref_id), span);
2323
2324         if let Some(variant_def_id) = variant_resolution {
2325             tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
2326                 let mut err = lint.build("ambiguous associated item");
2327                 let mut could_refer_to = |kind: DefKind, def_id, also| {
2328                     let note_msg = format!(
2329                         "`{}` could{} refer to the {} defined here",
2330                         assoc_ident,
2331                         also,
2332                         kind.descr(def_id)
2333                     );
2334                     err.span_note(tcx.def_span(def_id), &note_msg);
2335                 };
2336
2337                 could_refer_to(DefKind::Variant, variant_def_id, "");
2338                 could_refer_to(kind, item.def_id, " also");
2339
2340                 err.span_suggestion(
2341                     span,
2342                     "use fully-qualified syntax",
2343                     format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2344                     Applicability::MachineApplicable,
2345                 );
2346
2347                 err.emit();
2348             });
2349         }
2350         Ok((ty, kind, item.def_id))
2351     }
2352
2353     fn qpath_to_ty(
2354         &self,
2355         span: Span,
2356         opt_self_ty: Option<Ty<'tcx>>,
2357         item_def_id: DefId,
2358         trait_segment: &hir::PathSegment<'_>,
2359         item_segment: &hir::PathSegment<'_>,
2360     ) -> Ty<'tcx> {
2361         let tcx = self.tcx();
2362
2363         let trait_def_id = tcx.parent(item_def_id).unwrap();
2364
2365         debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2366
2367         let self_ty = if let Some(ty) = opt_self_ty {
2368             ty
2369         } else {
2370             let path_str = tcx.def_path_str(trait_def_id);
2371
2372             let def_id = self.item_def_id();
2373
2374             debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2375
2376             let parent_def_id = def_id
2377                 .and_then(|def_id| tcx.hir().as_local_hir_id(def_id))
2378                 .map(|hir_id| tcx.hir().get_parent_did(hir_id));
2379
2380             debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2381
2382             // If the trait in segment is the same as the trait defining the item,
2383             // use the `<Self as ..>` syntax in the error.
2384             let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
2385             let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2386
2387             let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2388                 "Self"
2389             } else {
2390                 "Type"
2391             };
2392
2393             self.report_ambiguous_associated_type(
2394                 span,
2395                 type_name,
2396                 &path_str,
2397                 item_segment.ident.name,
2398             );
2399             return tcx.types.err;
2400         };
2401
2402         debug!("qpath_to_ty: self_type={:?}", self_ty);
2403
2404         let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
2405
2406         let item_substs = self.create_substs_for_associated_item(
2407             tcx,
2408             span,
2409             item_def_id,
2410             item_segment,
2411             trait_ref.substs,
2412         );
2413
2414         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2415
2416         self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2417     }
2418
2419     pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2420         &self,
2421         segments: T,
2422     ) -> bool {
2423         let mut has_err = false;
2424         for segment in segments {
2425             let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2426             for arg in segment.generic_args().args {
2427                 let (span, kind) = match arg {
2428                     hir::GenericArg::Lifetime(lt) => {
2429                         if err_for_lt {
2430                             continue;
2431                         }
2432                         err_for_lt = true;
2433                         has_err = true;
2434                         (lt.span, "lifetime")
2435                     }
2436                     hir::GenericArg::Type(ty) => {
2437                         if err_for_ty {
2438                             continue;
2439                         }
2440                         err_for_ty = true;
2441                         has_err = true;
2442                         (ty.span, "type")
2443                     }
2444                     hir::GenericArg::Const(ct) => {
2445                         if err_for_ct {
2446                             continue;
2447                         }
2448                         err_for_ct = true;
2449                         (ct.span, "const")
2450                     }
2451                 };
2452                 let mut err = struct_span_err!(
2453                     self.tcx().sess,
2454                     span,
2455                     E0109,
2456                     "{} arguments are not allowed for this type",
2457                     kind,
2458                 );
2459                 err.span_label(span, format!("{} argument not allowed", kind));
2460                 err.emit();
2461                 if err_for_lt && err_for_ty && err_for_ct {
2462                     break;
2463                 }
2464             }
2465
2466             // Only emit the first error to avoid overloading the user with error messages.
2467             if let [binding, ..] = segment.generic_args().bindings {
2468                 has_err = true;
2469                 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2470             }
2471         }
2472         has_err
2473     }
2474
2475     pub fn prohibit_assoc_ty_binding(tcx: TyCtxt<'_>, span: Span) {
2476         let mut err = struct_span_err!(
2477             tcx.sess,
2478             span,
2479             E0229,
2480             "associated type bindings are not allowed here"
2481         );
2482         err.span_label(span, "associated type not allowed here").emit();
2483     }
2484
2485     // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2486     pub fn def_ids_for_value_path_segments(
2487         &self,
2488         segments: &[hir::PathSegment<'_>],
2489         self_ty: Option<Ty<'tcx>>,
2490         kind: DefKind,
2491         def_id: DefId,
2492     ) -> Vec<PathSeg> {
2493         // We need to extract the type parameters supplied by the user in
2494         // the path `path`. Due to the current setup, this is a bit of a
2495         // tricky-process; the problem is that resolve only tells us the
2496         // end-point of the path resolution, and not the intermediate steps.
2497         // Luckily, we can (at least for now) deduce the intermediate steps
2498         // just from the end-point.
2499         //
2500         // There are basically five cases to consider:
2501         //
2502         // 1. Reference to a constructor of a struct:
2503         //
2504         //        struct Foo<T>(...)
2505         //
2506         //    In this case, the parameters are declared in the type space.
2507         //
2508         // 2. Reference to a constructor of an enum variant:
2509         //
2510         //        enum E<T> { Foo(...) }
2511         //
2512         //    In this case, the parameters are defined in the type space,
2513         //    but may be specified either on the type or the variant.
2514         //
2515         // 3. Reference to a fn item or a free constant:
2516         //
2517         //        fn foo<T>() { }
2518         //
2519         //    In this case, the path will again always have the form
2520         //    `a::b::foo::<T>` where only the final segment should have
2521         //    type parameters. However, in this case, those parameters are
2522         //    declared on a value, and hence are in the `FnSpace`.
2523         //
2524         // 4. Reference to a method or an associated constant:
2525         //
2526         //        impl<A> SomeStruct<A> {
2527         //            fn foo<B>(...)
2528         //        }
2529         //
2530         //    Here we can have a path like
2531         //    `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2532         //    may appear in two places. The penultimate segment,
2533         //    `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2534         //    final segment, `foo::<B>` contains parameters in fn space.
2535         //
2536         // The first step then is to categorize the segments appropriately.
2537
2538         let tcx = self.tcx();
2539
2540         assert!(!segments.is_empty());
2541         let last = segments.len() - 1;
2542
2543         let mut path_segs = vec![];
2544
2545         match kind {
2546             // Case 1. Reference to a struct constructor.
2547             DefKind::Ctor(CtorOf::Struct, ..) => {
2548                 // Everything but the final segment should have no
2549                 // parameters at all.
2550                 let generics = tcx.generics_of(def_id);
2551                 // Variant and struct constructors use the
2552                 // generics of their parent type definition.
2553                 let generics_def_id = generics.parent.unwrap_or(def_id);
2554                 path_segs.push(PathSeg(generics_def_id, last));
2555             }
2556
2557             // Case 2. Reference to a variant constructor.
2558             DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2559                 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2560                 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2561                     debug_assert!(adt_def.is_enum());
2562                     (adt_def.did, last)
2563                 } else if last >= 1 && segments[last - 1].args.is_some() {
2564                     // Everything but the penultimate segment should have no
2565                     // parameters at all.
2566                     let mut def_id = def_id;
2567
2568                     // `DefKind::Ctor` -> `DefKind::Variant`
2569                     if let DefKind::Ctor(..) = kind {
2570                         def_id = tcx.parent(def_id).unwrap()
2571                     }
2572
2573                     // `DefKind::Variant` -> `DefKind::Enum`
2574                     let enum_def_id = tcx.parent(def_id).unwrap();
2575                     (enum_def_id, last - 1)
2576                 } else {
2577                     // FIXME: lint here recommending `Enum::<...>::Variant` form
2578                     // instead of `Enum::Variant::<...>` form.
2579
2580                     // Everything but the final segment should have no
2581                     // parameters at all.
2582                     let generics = tcx.generics_of(def_id);
2583                     // Variant and struct constructors use the
2584                     // generics of their parent type definition.
2585                     (generics.parent.unwrap_or(def_id), last)
2586                 };
2587                 path_segs.push(PathSeg(generics_def_id, index));
2588             }
2589
2590             // Case 3. Reference to a top-level value.
2591             DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2592                 path_segs.push(PathSeg(def_id, last));
2593             }
2594
2595             // Case 4. Reference to a method or associated const.
2596             DefKind::AssocFn | DefKind::AssocConst => {
2597                 if segments.len() >= 2 {
2598                     let generics = tcx.generics_of(def_id);
2599                     path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2600                 }
2601                 path_segs.push(PathSeg(def_id, last));
2602             }
2603
2604             kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2605         }
2606
2607         debug!("path_segs = {:?}", path_segs);
2608
2609         path_segs
2610     }
2611
2612     // Check a type `Path` and convert it to a `Ty`.
2613     pub fn res_to_ty(
2614         &self,
2615         opt_self_ty: Option<Ty<'tcx>>,
2616         path: &hir::Path<'_>,
2617         permit_variants: bool,
2618     ) -> Ty<'tcx> {
2619         let tcx = self.tcx();
2620
2621         debug!(
2622             "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2623             path.res, opt_self_ty, path.segments
2624         );
2625
2626         let span = path.span;
2627         match path.res {
2628             Res::Def(DefKind::OpaqueTy, did) => {
2629                 // Check for desugared `impl Trait`.
2630                 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2631                 let item_segment = path.segments.split_last().unwrap();
2632                 self.prohibit_generics(item_segment.1);
2633                 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2634                 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2635             }
2636             Res::Def(DefKind::Enum, did)
2637             | Res::Def(DefKind::TyAlias, did)
2638             | Res::Def(DefKind::Struct, did)
2639             | Res::Def(DefKind::Union, did)
2640             | Res::Def(DefKind::ForeignTy, did) => {
2641                 assert_eq!(opt_self_ty, None);
2642                 self.prohibit_generics(path.segments.split_last().unwrap().1);
2643                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2644             }
2645             Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2646                 // Convert "variant type" as if it were a real type.
2647                 // The resulting `Ty` is type of the variant's enum for now.
2648                 assert_eq!(opt_self_ty, None);
2649
2650                 let path_segs =
2651                     self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2652                 let generic_segs: FxHashSet<_> =
2653                     path_segs.iter().map(|PathSeg(_, index)| index).collect();
2654                 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2655                     |(index, seg)| {
2656                         if !generic_segs.contains(&index) { Some(seg) } else { None }
2657                     },
2658                 ));
2659
2660                 let PathSeg(def_id, index) = path_segs.last().unwrap();
2661                 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2662             }
2663             Res::Def(DefKind::TyParam, def_id) => {
2664                 assert_eq!(opt_self_ty, None);
2665                 self.prohibit_generics(path.segments);
2666
2667                 let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2668                 let item_id = tcx.hir().get_parent_node(hir_id);
2669                 let item_def_id = tcx.hir().local_def_id(item_id);
2670                 let generics = tcx.generics_of(item_def_id);
2671                 let index = generics.param_def_id_to_index[&def_id];
2672                 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2673             }
2674             Res::SelfTy(Some(_), None) => {
2675                 // `Self` in trait or type alias.
2676                 assert_eq!(opt_self_ty, None);
2677                 self.prohibit_generics(path.segments);
2678                 tcx.types.self_param
2679             }
2680             Res::SelfTy(_, Some(def_id)) => {
2681                 // `Self` in impl (we know the concrete type).
2682                 assert_eq!(opt_self_ty, None);
2683                 self.prohibit_generics(path.segments);
2684                 // Try to evaluate any array length constants.
2685                 self.normalize_ty(span, tcx.at(span).type_of(def_id))
2686             }
2687             Res::Def(DefKind::AssocTy, def_id) => {
2688                 debug_assert!(path.segments.len() >= 2);
2689                 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2690                 self.qpath_to_ty(
2691                     span,
2692                     opt_self_ty,
2693                     def_id,
2694                     &path.segments[path.segments.len() - 2],
2695                     path.segments.last().unwrap(),
2696                 )
2697             }
2698             Res::PrimTy(prim_ty) => {
2699                 assert_eq!(opt_self_ty, None);
2700                 self.prohibit_generics(path.segments);
2701                 match prim_ty {
2702                     hir::PrimTy::Bool => tcx.types.bool,
2703                     hir::PrimTy::Char => tcx.types.char,
2704                     hir::PrimTy::Int(it) => tcx.mk_mach_int(it),
2705                     hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(uit),
2706                     hir::PrimTy::Float(ft) => tcx.mk_mach_float(ft),
2707                     hir::PrimTy::Str => tcx.mk_str(),
2708                 }
2709             }
2710             Res::Err => {
2711                 self.set_tainted_by_errors();
2712                 return self.tcx().types.err;
2713             }
2714             _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2715         }
2716     }
2717
2718     /// Parses the programmer's textual representation of a type into our
2719     /// internal notion of a type.
2720     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2721         debug!("ast_ty_to_ty(id={:?}, ast_ty={:?} ty_ty={:?})", ast_ty.hir_id, ast_ty, ast_ty.kind);
2722
2723         let tcx = self.tcx();
2724
2725         let result_ty = match ast_ty.kind {
2726             hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2727             hir::TyKind::Ptr(ref mt) => {
2728                 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2729             }
2730             hir::TyKind::Rptr(ref region, ref mt) => {
2731                 let r = self.ast_region_to_region(region, None);
2732                 debug!("ast_ty_to_ty: r={:?}", r);
2733                 let t = self.ast_ty_to_ty(&mt.ty);
2734                 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2735             }
2736             hir::TyKind::Never => tcx.types.never,
2737             hir::TyKind::Tup(ref fields) => {
2738                 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2739             }
2740             hir::TyKind::BareFn(ref bf) => {
2741                 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2742                 tcx.mk_fn_ptr(self.ty_of_fn(bf.unsafety, bf.abi, &bf.decl, &[], None))
2743             }
2744             hir::TyKind::TraitObject(ref bounds, ref lifetime) => {
2745                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime)
2746             }
2747             hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2748                 debug!("ast_ty_to_ty: maybe_qself={:?} path={:?}", maybe_qself, path);
2749                 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2750                 self.res_to_ty(opt_self_ty, path, false)
2751             }
2752             hir::TyKind::Def(item_id, ref lifetimes) => {
2753                 let did = tcx.hir().local_def_id(item_id.id);
2754                 self.impl_trait_ty_to_ty(did, lifetimes)
2755             }
2756             hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2757                 debug!("ast_ty_to_ty: qself={:?} segment={:?}", qself, segment);
2758                 let ty = self.ast_ty_to_ty(qself);
2759
2760                 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2761                     path.res
2762                 } else {
2763                     Res::Err
2764                 };
2765                 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2766                     .map(|(ty, _, _)| ty)
2767                     .unwrap_or(tcx.types.err)
2768             }
2769             hir::TyKind::Array(ref ty, ref length) => {
2770                 let length = self.ast_const_to_const(length, tcx.types.usize);
2771                 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2772                 self.normalize_ty(ast_ty.span, array_ty)
2773             }
2774             hir::TyKind::Typeof(ref _e) => {
2775                 struct_span_err!(
2776                     tcx.sess,
2777                     ast_ty.span,
2778                     E0516,
2779                     "`typeof` is a reserved keyword but unimplemented"
2780                 )
2781                 .span_label(ast_ty.span, "reserved keyword")
2782                 .emit();
2783
2784                 tcx.types.err
2785             }
2786             hir::TyKind::Infer => {
2787                 // Infer also appears as the type of arguments or return
2788                 // values in a ExprKind::Closure, or as
2789                 // the type of local variables. Both of these cases are
2790                 // handled specially and will not descend into this routine.
2791                 self.ty_infer(None, ast_ty.span)
2792             }
2793             hir::TyKind::Err => tcx.types.err,
2794         };
2795
2796         debug!("ast_ty_to_ty: result_ty={:?}", result_ty);
2797
2798         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2799         result_ty
2800     }
2801
2802     /// Returns the `DefId` of the constant parameter that the provided expression is a path to.
2803     pub fn const_param_def_id(&self, expr: &hir::Expr<'_>) -> Option<DefId> {
2804         // Unwrap a block, so that e.g. `{ P }` is recognised as a parameter. Const arguments
2805         // currently have to be wrapped in curly brackets, so it's necessary to special-case.
2806         let expr = match &expr.kind {
2807             ExprKind::Block(block, _) if block.stmts.is_empty() && block.expr.is_some() => {
2808                 block.expr.as_ref().unwrap()
2809             }
2810             _ => expr,
2811         };
2812
2813         match &expr.kind {
2814             ExprKind::Path(hir::QPath::Resolved(_, path)) => match path.res {
2815                 Res::Def(DefKind::ConstParam, did) => Some(did),
2816                 _ => None,
2817             },
2818             _ => None,
2819         }
2820     }
2821
2822     pub fn ast_const_to_const(
2823         &self,
2824         ast_const: &hir::AnonConst,
2825         ty: Ty<'tcx>,
2826     ) -> &'tcx ty::Const<'tcx> {
2827         debug!("ast_const_to_const(id={:?}, ast_const={:?})", ast_const.hir_id, ast_const);
2828
2829         let tcx = self.tcx();
2830         let def_id = tcx.hir().local_def_id(ast_const.hir_id);
2831
2832         let expr = &tcx.hir().body(ast_const.body).value;
2833
2834         let lit_input = match expr.kind {
2835             hir::ExprKind::Lit(ref lit) => Some(LitToConstInput { lit: &lit.node, ty, neg: false }),
2836             hir::ExprKind::Unary(hir::UnOp::UnNeg, ref expr) => match expr.kind {
2837                 hir::ExprKind::Lit(ref lit) => {
2838                     Some(LitToConstInput { lit: &lit.node, ty, neg: true })
2839                 }
2840                 _ => None,
2841             },
2842             _ => None,
2843         };
2844
2845         if let Some(lit_input) = lit_input {
2846             // If an error occurred, ignore that it's a literal and leave reporting the error up to
2847             // mir.
2848             if let Ok(c) = tcx.at(expr.span).lit_to_const(lit_input) {
2849                 return c;
2850             } else {
2851                 tcx.sess.delay_span_bug(expr.span, "ast_const_to_const: couldn't lit_to_const");
2852             }
2853         }
2854
2855         let kind = if let Some(def_id) = self.const_param_def_id(expr) {
2856             // Find the name and index of the const parameter by indexing the generics of the
2857             // parent item and construct a `ParamConst`.
2858             let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
2859             let item_id = tcx.hir().get_parent_node(hir_id);
2860             let item_def_id = tcx.hir().local_def_id(item_id);
2861             let generics = tcx.generics_of(item_def_id);
2862             let index = generics.param_def_id_to_index[&tcx.hir().local_def_id(hir_id)];
2863             let name = tcx.hir().name(hir_id);
2864             ty::ConstKind::Param(ty::ParamConst::new(index, name))
2865         } else {
2866             ty::ConstKind::Unevaluated(def_id, InternalSubsts::identity_for_item(tcx, def_id), None)
2867         };
2868         tcx.mk_const(ty::Const { val: kind, ty })
2869     }
2870
2871     pub fn impl_trait_ty_to_ty(
2872         &self,
2873         def_id: DefId,
2874         lifetimes: &[hir::GenericArg<'_>],
2875     ) -> Ty<'tcx> {
2876         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2877         let tcx = self.tcx();
2878
2879         let generics = tcx.generics_of(def_id);
2880
2881         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2882         let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2883             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2884                 // Our own parameters are the resolved lifetimes.
2885                 match param.kind {
2886                     GenericParamDefKind::Lifetime => {
2887                         if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2888                             self.ast_region_to_region(lifetime, None).into()
2889                         } else {
2890                             bug!()
2891                         }
2892                     }
2893                     _ => bug!(),
2894                 }
2895             } else {
2896                 // Replace all parent lifetimes with `'static`.
2897                 match param.kind {
2898                     GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
2899                     _ => tcx.mk_param_from_def(param),
2900                 }
2901             }
2902         });
2903         debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2904
2905         let ty = tcx.mk_opaque(def_id, substs);
2906         debug!("impl_trait_ty_to_ty: {}", ty);
2907         ty
2908     }
2909
2910     pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2911         match ty.kind {
2912             hir::TyKind::Infer if expected_ty.is_some() => {
2913                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2914                 expected_ty.unwrap()
2915             }
2916             _ => self.ast_ty_to_ty(ty),
2917         }
2918     }
2919
2920     pub fn ty_of_fn(
2921         &self,
2922         unsafety: hir::Unsafety,
2923         abi: abi::Abi,
2924         decl: &hir::FnDecl<'_>,
2925         generic_params: &[hir::GenericParam<'_>],
2926         ident_span: Option<Span>,
2927     ) -> ty::PolyFnSig<'tcx> {
2928         debug!("ty_of_fn");
2929
2930         let tcx = self.tcx();
2931
2932         // We proactively collect all the inferred type params to emit a single error per fn def.
2933         let mut visitor = PlaceholderHirTyCollector::default();
2934         for ty in decl.inputs {
2935             visitor.visit_ty(ty);
2936         }
2937         let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2938         let output_ty = match decl.output {
2939             hir::FnRetTy::Return(ref output) => {
2940                 visitor.visit_ty(output);
2941                 self.ast_ty_to_ty(output)
2942             }
2943             hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2944         };
2945
2946         debug!("ty_of_fn: output_ty={:?}", output_ty);
2947
2948         let bare_fn_ty =
2949             ty::Binder::bind(tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi));
2950
2951         if !self.allow_ty_infer() {
2952             // We always collect the spans for placeholder types when evaluating `fn`s, but we
2953             // only want to emit an error complaining about them if infer types (`_`) are not
2954             // allowed. `allow_ty_infer` gates this behavior.
2955             crate::collect::placeholder_type_error(
2956                 tcx,
2957                 ident_span.map(|sp| sp.shrink_to_hi()).unwrap_or(DUMMY_SP),
2958                 generic_params,
2959                 visitor.0,
2960                 ident_span.is_some(),
2961             );
2962         }
2963
2964         // Find any late-bound regions declared in return type that do
2965         // not appear in the arguments. These are not well-formed.
2966         //
2967         // Example:
2968         //     for<'a> fn() -> &'a str <-- 'a is bad
2969         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2970         let inputs = bare_fn_ty.inputs();
2971         let late_bound_in_args =
2972             tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2973         let output = bare_fn_ty.output();
2974         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2975         for br in late_bound_in_ret.difference(&late_bound_in_args) {
2976             let lifetime_name = match *br {
2977                 ty::BrNamed(_, name) => format!("lifetime `{}`,", name),
2978                 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2979             };
2980             let mut err = struct_span_err!(
2981                 tcx.sess,
2982                 decl.output.span(),
2983                 E0581,
2984                 "return type references {} \
2985                                             which is not constrained by the fn input types",
2986                 lifetime_name
2987             );
2988             if let ty::BrAnon(_) = *br {
2989                 // The only way for an anonymous lifetime to wind up
2990                 // in the return type but **also** be unconstrained is
2991                 // if it only appears in "associated types" in the
2992                 // input. See #47511 for an example. In this case,
2993                 // though we can easily give a hint that ought to be
2994                 // relevant.
2995                 err.note(
2996                     "lifetimes appearing in an associated type \
2997                           are not considered constrained",
2998                 );
2999             }
3000             err.emit();
3001         }
3002
3003         bare_fn_ty
3004     }
3005
3006     /// Given the bounds on an object, determines what single region bound (if any) we can
3007     /// use to summarize this type. The basic idea is that we will use the bound the user
3008     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
3009     /// for region bounds. It may be that we can derive no bound at all, in which case
3010     /// we return `None`.
3011     fn compute_object_lifetime_bound(
3012         &self,
3013         span: Span,
3014         existential_predicates: ty::Binder<&'tcx ty::List<ty::ExistentialPredicate<'tcx>>>,
3015     ) -> Option<ty::Region<'tcx>> // if None, use the default
3016     {
3017         let tcx = self.tcx();
3018
3019         debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
3020
3021         // No explicit region bound specified. Therefore, examine trait
3022         // bounds and see if we can derive region bounds from those.
3023         let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3024
3025         // If there are no derived region bounds, then report back that we
3026         // can find no region bound. The caller will use the default.
3027         if derived_region_bounds.is_empty() {
3028             return None;
3029         }
3030
3031         // If any of the derived region bounds are 'static, that is always
3032         // the best choice.
3033         if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
3034             return Some(tcx.lifetimes.re_static);
3035         }
3036
3037         // Determine whether there is exactly one unique region in the set
3038         // of derived region bounds. If so, use that. Otherwise, report an
3039         // error.
3040         let r = derived_region_bounds[0];
3041         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3042             struct_span_err!(
3043                 tcx.sess,
3044                 span,
3045                 E0227,
3046                 "ambiguous lifetime bound, explicit lifetime bound required"
3047             )
3048             .emit();
3049         }
3050         return Some(r);
3051     }
3052 }
3053
3054 /// Collects together a list of bounds that are applied to some type,
3055 /// after they've been converted into `ty` form (from the HIR
3056 /// representations). These lists of bounds occur in many places in
3057 /// Rust's syntax:
3058 ///
3059 /// ```
3060 /// trait Foo: Bar + Baz { }
3061 ///            ^^^^^^^^^ supertrait list bounding the `Self` type parameter
3062 ///
3063 /// fn foo<T: Bar + Baz>() { }
3064 ///           ^^^^^^^^^ bounding the type parameter `T`
3065 ///
3066 /// impl dyn Bar + Baz
3067 ///          ^^^^^^^^^ bounding the forgotten dynamic type
3068 /// ```
3069 ///
3070 /// Our representation is a bit mixed here -- in some cases, we
3071 /// include the self type (e.g., `trait_bounds`) but in others we do
3072 #[derive(Default, PartialEq, Eq, Clone, Debug)]
3073 pub struct Bounds<'tcx> {
3074     /// A list of region bounds on the (implicit) self type. So if you
3075     /// had `T: 'a + 'b` this might would be a list `['a, 'b]` (but
3076     /// the `T` is not explicitly included).
3077     pub region_bounds: Vec<(ty::Region<'tcx>, Span)>,
3078
3079     /// A list of trait bounds. So if you had `T: Debug` this would be
3080     /// `T: Debug`. Note that the self-type is explicit here.
3081     pub trait_bounds: Vec<(ty::PolyTraitRef<'tcx>, Span, Constness)>,
3082
3083     /// A list of projection equality bounds. So if you had `T:
3084     /// Iterator<Item = u32>` this would include `<T as
3085     /// Iterator>::Item => u32`. Note that the self-type is explicit
3086     /// here.
3087     pub projection_bounds: Vec<(ty::PolyProjectionPredicate<'tcx>, Span)>,
3088
3089     /// `Some` if there is *no* `?Sized` predicate. The `span`
3090     /// is the location in the source of the `T` declaration which can
3091     /// be cited as the source of the `T: Sized` requirement.
3092     pub implicitly_sized: Option<Span>,
3093 }
3094
3095 impl<'tcx> Bounds<'tcx> {
3096     /// Converts a bounds list into a flat set of predicates (like
3097     /// where-clauses). Because some of our bounds listings (e.g.,
3098     /// regions) don't include the self-type, you must supply the
3099     /// self-type here (the `param_ty` parameter).
3100     pub fn predicates(
3101         &self,
3102         tcx: TyCtxt<'tcx>,
3103         param_ty: Ty<'tcx>,
3104     ) -> Vec<(ty::Predicate<'tcx>, Span)> {
3105         // If it could be sized, and is, add the `Sized` predicate.
3106         let sized_predicate = self.implicitly_sized.and_then(|span| {
3107             tcx.lang_items().sized_trait().map(|sized| {
3108                 let trait_ref = ty::Binder::bind(ty::TraitRef {
3109                     def_id: sized,
3110                     substs: tcx.mk_substs_trait(param_ty, &[]),
3111                 });
3112                 (trait_ref.without_const().to_predicate(), span)
3113             })
3114         });
3115
3116         sized_predicate
3117             .into_iter()
3118             .chain(
3119                 self.region_bounds
3120                     .iter()
3121                     .map(|&(region_bound, span)| {
3122                         // Account for the binder being introduced below; no need to shift `param_ty`
3123                         // because, at present at least, it either only refers to early-bound regions,
3124                         // or it's a generic associated type that deliberately has escaping bound vars.
3125                         let region_bound = ty::fold::shift_region(tcx, region_bound, 1);
3126                         let outlives = ty::OutlivesPredicate(param_ty, region_bound);
3127                         (ty::Binder::bind(outlives).to_predicate(), span)
3128                     })
3129                     .chain(self.trait_bounds.iter().map(|&(bound_trait_ref, span, constness)| {
3130                         let predicate = bound_trait_ref.with_constness(constness).to_predicate();
3131                         (predicate, span)
3132                     }))
3133                     .chain(
3134                         self.projection_bounds
3135                             .iter()
3136                             .map(|&(projection, span)| (projection.to_predicate(), span)),
3137                     ),
3138             )
3139             .collect()
3140     }
3141 }