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