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