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