]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/astconv/mod.rs
Rollup merge of #103890 - notriddle:notriddle/mobile-rustdoc-padding-top, r=Guillaume...
[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::DynKind;
30 use rustc_middle::ty::GenericParamDefKind;
31 use rustc_middle::ty::{
32     self, Const, DefIdTree, EarlyBinder, IsSuggestable, Ty, TyCtxt, TypeVisitable,
33 };
34 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, BARE_TRAIT_OBJECTS};
35 use rustc_span::edition::Edition;
36 use rustc_span::lev_distance::find_best_match_for_name;
37 use rustc_span::symbol::{kw, Ident, Symbol};
38 use rustc_span::{sym, Span};
39 use rustc_target::spec::abi;
40 use rustc_trait_selection::traits;
41 use rustc_trait_selection::traits::astconv_object_safety_violations;
42 use rustc_trait_selection::traits::error_reporting::{
43     report_object_safety_error, suggestions::NextTypeParamName,
44 };
45 use rustc_trait_selection::traits::wf::object_region_bounds;
46
47 use smallvec::{smallvec, SmallVec};
48 use std::collections::BTreeSet;
49 use std::slice;
50
51 #[derive(Debug)]
52 pub struct PathSeg(pub DefId, pub usize);
53
54 pub trait AstConv<'tcx> {
55     fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
56
57     fn item_def_id(&self) -> DefId;
58
59     /// Returns predicates in scope of the form `X: Foo<T>`, where `X`
60     /// is a type parameter `X` with the given id `def_id` and T
61     /// matches `assoc_name`. This is a subset of the full set of
62     /// predicates.
63     ///
64     /// This is used for one specific purpose: resolving "short-hand"
65     /// associated type references like `T::Item`. In principle, we
66     /// would do that by first getting the full set of predicates in
67     /// scope and then filtering down to find those that apply to `T`,
68     /// but this can lead to cycle errors. The problem is that we have
69     /// to do this resolution *in order to create the predicates in
70     /// the first place*. Hence, we have this "special pass".
71     fn get_type_parameter_bounds(
72         &self,
73         span: Span,
74         def_id: DefId,
75         assoc_name: Ident,
76     ) -> ty::GenericPredicates<'tcx>;
77
78     /// Returns the lifetime to use when a lifetime is omitted (and not elided).
79     fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
80     -> Option<ty::Region<'tcx>>;
81
82     /// Returns the type to use when a type is omitted.
83     fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
84
85     /// Returns `true` if `_` is allowed in type signatures in the current context.
86     fn allow_ty_infer(&self) -> bool;
87
88     /// Returns the const to use when a const is omitted.
89     fn ct_infer(
90         &self,
91         ty: Ty<'tcx>,
92         param: Option<&ty::GenericParamDef>,
93         span: Span,
94     ) -> Const<'tcx>;
95
96     /// Projecting an associated type from a (potentially)
97     /// higher-ranked trait reference is more complicated, because of
98     /// the possibility of late-bound regions appearing in the
99     /// associated type binding. This is not legal in function
100     /// signatures for that reason. In a function body, we can always
101     /// handle it because we can use inference variables to remove the
102     /// late-bound regions.
103     fn projected_ty_from_poly_trait_ref(
104         &self,
105         span: Span,
106         item_def_id: DefId,
107         item_segment: &hir::PathSegment<'_>,
108         poly_trait_ref: ty::PolyTraitRef<'tcx>,
109     ) -> Ty<'tcx>;
110
111     /// Normalize an associated type coming from the user.
112     fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
113
114     /// Invoked when we encounter an error from some prior pass
115     /// (e.g., resolve) that is translated into a ty-error. This is
116     /// used to help suppress derived errors typeck might otherwise
117     /// report.
118     fn set_tainted_by_errors(&self);
119
120     fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
121 }
122
123 #[derive(Debug)]
124 struct ConvertedBinding<'a, 'tcx> {
125     hir_id: hir::HirId,
126     item_name: Ident,
127     kind: ConvertedBindingKind<'a, 'tcx>,
128     gen_args: &'a GenericArgs<'a>,
129     span: Span,
130 }
131
132 #[derive(Debug)]
133 enum ConvertedBindingKind<'a, 'tcx> {
134     Equality(ty::Term<'tcx>),
135     Constraint(&'a [hir::GenericBound<'a>]),
136 }
137
138 /// New-typed boolean indicating whether explicit late-bound lifetimes
139 /// are present in a set of generic arguments.
140 ///
141 /// For example if we have some method `fn f<'a>(&'a self)` implemented
142 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
143 /// is late-bound so should not be provided explicitly. Thus, if `f` is
144 /// instantiated with some generic arguments providing `'a` explicitly,
145 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
146 /// can provide an appropriate diagnostic later.
147 #[derive(Copy, Clone, PartialEq, Debug)]
148 pub enum ExplicitLateBound {
149     Yes,
150     No,
151 }
152
153 #[derive(Copy, Clone, PartialEq)]
154 pub enum IsMethodCall {
155     Yes,
156     No,
157 }
158
159 /// Denotes the "position" of a generic argument, indicating if it is a generic type,
160 /// generic function or generic method call.
161 #[derive(Copy, Clone, PartialEq)]
162 pub(crate) enum GenericArgPosition {
163     Type,
164     Value, // e.g., functions
165     MethodCall,
166 }
167
168 /// A marker denoting that the generic arguments that were
169 /// provided did not match the respective generic parameters.
170 #[derive(Clone, Default, Debug)]
171 pub struct GenericArgCountMismatch {
172     /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
173     pub reported: Option<ErrorGuaranteed>,
174     /// A list of spans of arguments provided that were not valid.
175     pub invalid_args: Vec<Span>,
176 }
177
178 /// Decorates the result of a generic argument count mismatch
179 /// check with whether explicit late bounds were provided.
180 #[derive(Clone, Debug)]
181 pub struct GenericArgCountResult {
182     pub explicit_late_bound: ExplicitLateBound,
183     pub correct: Result<(), GenericArgCountMismatch>,
184 }
185
186 pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> {
187     fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
188
189     fn provided_kind(
190         &mut self,
191         param: &ty::GenericParamDef,
192         arg: &GenericArg<'_>,
193     ) -> subst::GenericArg<'tcx>;
194
195     fn inferred_kind(
196         &mut self,
197         substs: Option<&[subst::GenericArg<'tcx>]>,
198         param: &ty::GenericParamDef,
199         infer_args: bool,
200     ) -> subst::GenericArg<'tcx>;
201 }
202
203 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
204     #[instrument(level = "debug", skip(self), ret)]
205     pub fn ast_region_to_region(
206         &self,
207         lifetime: &hir::Lifetime,
208         def: Option<&ty::GenericParamDef>,
209     ) -> ty::Region<'tcx> {
210         let tcx = self.tcx();
211         let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
212
213         match tcx.named_region(lifetime.hir_id) {
214             Some(rl::Region::Static) => tcx.lifetimes.re_static,
215
216             Some(rl::Region::LateBound(debruijn, index, def_id)) => {
217                 let name = lifetime_name(def_id.expect_local());
218                 let br = ty::BoundRegion {
219                     var: ty::BoundVar::from_u32(index),
220                     kind: ty::BrNamed(def_id, name),
221                 };
222                 tcx.mk_region(ty::ReLateBound(debruijn, br))
223             }
224
225             Some(rl::Region::EarlyBound(def_id)) => {
226                 let name = tcx.hir().ty_param_name(def_id.expect_local());
227                 let item_def_id = tcx.hir().ty_param_owner(def_id.expect_local());
228                 let generics = tcx.generics_of(item_def_id);
229                 let index = generics.param_def_id_to_index[&def_id];
230                 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, index, name }))
231             }
232
233             Some(rl::Region::Free(scope, id)) => {
234                 let name = lifetime_name(id.expect_local());
235                 tcx.mk_region(ty::ReFree(ty::FreeRegion {
236                     scope,
237                     bound_region: ty::BrNamed(id, name),
238                 }))
239
240                 // (*) -- not late-bound, won't change
241             }
242
243             None => {
244                 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
245                     debug!(?lifetime, "unelided lifetime in signature");
246
247                     // This indicates an illegal lifetime
248                     // elision. `resolve_lifetime` should have
249                     // reported an error in this case -- but if
250                     // not, let's error out.
251                     tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
252
253                     // Supply some dummy value. We don't have an
254                     // `re_error`, annoyingly, so use `'static`.
255                     tcx.lifetimes.re_static
256                 })
257             }
258         }
259     }
260
261     /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
262     /// returns an appropriate set of substitutions for this particular reference to `I`.
263     pub fn ast_path_substs_for_ty(
264         &self,
265         span: Span,
266         def_id: DefId,
267         item_segment: &hir::PathSegment<'_>,
268     ) -> SubstsRef<'tcx> {
269         let (substs, _) = self.create_substs_for_ast_path(
270             span,
271             def_id,
272             &[],
273             item_segment,
274             item_segment.args(),
275             item_segment.infer_args,
276             None,
277             None,
278         );
279         if let Some(b) = item_segment.args().bindings.first() {
280             Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
281         }
282
283         substs
284     }
285
286     /// Given the type/lifetime/const arguments provided to some path (along with
287     /// an implicit `Self`, if this is a trait reference), returns the complete
288     /// set of substitutions. This may involve applying defaulted type parameters.
289     /// Constraints on associated types are created from `create_assoc_bindings_for_generic_args`.
290     ///
291     /// Example:
292     ///
293     /// ```ignore (illustrative)
294     ///    T: std::ops::Index<usize, Output = u32>
295     /// // ^1 ^^^^^^^^^^^^^^2 ^^^^3  ^^^^^^^^^^^4
296     /// ```
297     ///
298     /// 1. The `self_ty` here would refer to the type `T`.
299     /// 2. The path in question is the path to the trait `std::ops::Index`,
300     ///    which will have been resolved to a `def_id`
301     /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
302     ///    parameters are returned in the `SubstsRef`, the associated type bindings like
303     ///    `Output = u32` are returned from `create_assoc_bindings_for_generic_args`.
304     ///
305     /// Note that the type listing given here is *exactly* what the user provided.
306     ///
307     /// For (generic) associated types
308     ///
309     /// ```ignore (illustrative)
310     /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
311     /// ```
312     ///
313     /// We have the parent substs are the substs for the parent trait:
314     /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
315     /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
316     /// lists: `[Vec<u8>, u8, 'a]`.
317     #[instrument(level = "debug", skip(self, span), ret)]
318     fn create_substs_for_ast_path<'a>(
319         &self,
320         span: Span,
321         def_id: DefId,
322         parent_substs: &[subst::GenericArg<'tcx>],
323         seg: &hir::PathSegment<'_>,
324         generic_args: &'a hir::GenericArgs<'_>,
325         infer_args: bool,
326         self_ty: Option<Ty<'tcx>>,
327         constness: Option<ty::BoundConstness>,
328     ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
329         // If the type is parameterized by this region, then replace this
330         // region with the current anon region binding (in other words,
331         // whatever & would get replaced with).
332
333         let tcx = self.tcx();
334         let generics = tcx.generics_of(def_id);
335         debug!("generics: {:?}", generics);
336
337         if generics.has_self {
338             if generics.parent.is_some() {
339                 // The parent is a trait so it should have at least one subst
340                 // for the `Self` type.
341                 assert!(!parent_substs.is_empty())
342             } else {
343                 // This item (presumably a trait) needs a self-type.
344                 assert!(self_ty.is_some());
345             }
346         } else {
347             assert!(self_ty.is_none() && parent_substs.is_empty());
348         }
349
350         let arg_count = Self::check_generic_arg_count(
351             tcx,
352             span,
353             def_id,
354             seg,
355             generics,
356             generic_args,
357             GenericArgPosition::Type,
358             self_ty.is_some(),
359             infer_args,
360         );
361
362         // Skip processing if type has no generic parameters.
363         // Traits always have `Self` as a generic parameter, which means they will not return early
364         // here and so associated type bindings will be handled regardless of whether there are any
365         // non-`Self` generic parameters.
366         if generics.params.is_empty() {
367             return (tcx.intern_substs(parent_substs), arg_count);
368         }
369
370         struct SubstsForAstPathCtxt<'a, 'tcx> {
371             astconv: &'a (dyn AstConv<'tcx> + 'a),
372             def_id: DefId,
373             generic_args: &'a GenericArgs<'a>,
374             span: Span,
375             inferred_params: Vec<Span>,
376             infer_args: bool,
377         }
378
379         impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> {
380             fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) {
381                 if did == self.def_id {
382                     (Some(self.generic_args), self.infer_args)
383                 } else {
384                     // The last component of this tuple is unimportant.
385                     (None, false)
386                 }
387             }
388
389             fn provided_kind(
390                 &mut self,
391                 param: &ty::GenericParamDef,
392                 arg: &GenericArg<'_>,
393             ) -> subst::GenericArg<'tcx> {
394                 let tcx = self.astconv.tcx();
395
396                 let mut handle_ty_args = |has_default, ty: &hir::Ty<'_>| {
397                     if has_default {
398                         tcx.check_optional_stability(
399                             param.def_id,
400                             Some(arg.hir_id()),
401                             arg.span(),
402                             None,
403                             AllowUnstable::No,
404                             |_, _| {
405                                 // Default generic parameters may not be marked
406                                 // with stability attributes, i.e. when the
407                                 // default parameter was defined at the same time
408                                 // as the rest of the type. As such, we ignore missing
409                                 // stability attributes.
410                             },
411                         );
412                     }
413                     if let (hir::TyKind::Infer, false) = (&ty.kind, self.astconv.allow_ty_infer()) {
414                         self.inferred_params.push(ty.span);
415                         tcx.ty_error().into()
416                     } else {
417                         self.astconv.ast_ty_to_ty(ty).into()
418                     }
419                 };
420
421                 match (&param.kind, arg) {
422                     (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
423                         self.astconv.ast_region_to_region(lt, Some(param)).into()
424                     }
425                     (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
426                         handle_ty_args(has_default, ty)
427                     }
428                     (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
429                         handle_ty_args(has_default, &inf.to_ty())
430                     }
431                     (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
432                         ty::Const::from_opt_const_arg_anon_const(
433                             tcx,
434                             ty::WithOptConstParam {
435                                 did: tcx.hir().local_def_id(ct.value.hir_id),
436                                 const_param_did: Some(param.def_id),
437                             },
438                         )
439                         .into()
440                     }
441                     (&GenericParamDefKind::Const { .. }, hir::GenericArg::Infer(inf)) => {
442                         let ty = tcx.at(self.span).type_of(param.def_id);
443                         if self.astconv.allow_ty_infer() {
444                             self.astconv.ct_infer(ty, Some(param), inf.span).into()
445                         } else {
446                             self.inferred_params.push(inf.span);
447                             tcx.const_error(ty).into()
448                         }
449                     }
450                     _ => unreachable!(),
451                 }
452             }
453
454             fn inferred_kind(
455                 &mut self,
456                 substs: Option<&[subst::GenericArg<'tcx>]>,
457                 param: &ty::GenericParamDef,
458                 infer_args: bool,
459             ) -> subst::GenericArg<'tcx> {
460                 let tcx = self.astconv.tcx();
461                 match param.kind {
462                     GenericParamDefKind::Lifetime => self
463                         .astconv
464                         .re_infer(Some(param), self.span)
465                         .unwrap_or_else(|| {
466                             debug!(?param, "unelided lifetime in signature");
467
468                             // This indicates an illegal lifetime in a non-assoc-trait position
469                             tcx.sess.delay_span_bug(self.span, "unelided lifetime in signature");
470
471                             // Supply some dummy value. We don't have an
472                             // `re_error`, annoyingly, so use `'static`.
473                             tcx.lifetimes.re_static
474                         })
475                         .into(),
476                     GenericParamDefKind::Type { has_default, .. } => {
477                         if !infer_args && has_default {
478                             // No type parameter provided, but a default exists.
479                             let substs = substs.unwrap();
480                             if substs.iter().any(|arg| match arg.unpack() {
481                                 GenericArgKind::Type(ty) => ty.references_error(),
482                                 _ => false,
483                             }) {
484                                 // Avoid ICE #86756 when type error recovery goes awry.
485                                 return tcx.ty_error().into();
486                             }
487                             self.astconv
488                                 .normalize_ty(
489                                     self.span,
490                                     EarlyBinder(tcx.at(self.span).type_of(param.def_id))
491                                         .subst(tcx, substs),
492                                 )
493                                 .into()
494                         } else if infer_args {
495                             self.astconv.ty_infer(Some(param), self.span).into()
496                         } else {
497                             // We've already errored above about the mismatch.
498                             tcx.ty_error().into()
499                         }
500                     }
501                     GenericParamDefKind::Const { has_default } => {
502                         let ty = tcx.at(self.span).type_of(param.def_id);
503                         if ty.references_error() {
504                             return tcx.const_error(ty).into();
505                         }
506                         if !infer_args && has_default {
507                             tcx.bound_const_param_default(param.def_id)
508                                 .subst(tcx, substs.unwrap())
509                                 .into()
510                         } else {
511                             if infer_args {
512                                 self.astconv.ct_infer(ty, Some(param), self.span).into()
513                             } else {
514                                 // We've already errored above about the mismatch.
515                                 tcx.const_error(ty).into()
516                             }
517                         }
518                     }
519                 }
520             }
521         }
522
523         let mut substs_ctx = SubstsForAstPathCtxt {
524             astconv: self,
525             def_id,
526             span,
527             generic_args,
528             inferred_params: vec![],
529             infer_args,
530         };
531         let substs = Self::create_substs_for_generic_args(
532             tcx,
533             def_id,
534             parent_substs,
535             self_ty.is_some(),
536             self_ty,
537             &arg_count,
538             &mut substs_ctx,
539         );
540
541         if let Some(ty::BoundConstness::ConstIfConst) = constness
542             && generics.has_self && !tcx.has_attr(def_id, sym::const_trait)
543         {
544             tcx.sess.emit_err(crate::errors::ConstBoundForNonConstTrait { span } );
545         }
546
547         (substs, arg_count)
548     }
549
550     fn create_assoc_bindings_for_generic_args<'a>(
551         &self,
552         generic_args: &'a hir::GenericArgs<'_>,
553     ) -> Vec<ConvertedBinding<'a, 'tcx>> {
554         // Convert associated-type bindings or constraints into a separate vector.
555         // Example: Given this:
556         //
557         //     T: Iterator<Item = u32>
558         //
559         // The `T` is passed in as a self-type; the `Item = u32` is
560         // not a "type parameter" of the `Iterator` trait, but rather
561         // a restriction on `<T as Iterator>::Item`, so it is passed
562         // back separately.
563         let assoc_bindings = generic_args
564             .bindings
565             .iter()
566             .map(|binding| {
567                 let kind = match binding.kind {
568                     hir::TypeBindingKind::Equality { ref term } => match term {
569                         hir::Term::Ty(ref ty) => {
570                             ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty).into())
571                         }
572                         hir::Term::Const(ref c) => {
573                             let local_did = self.tcx().hir().local_def_id(c.hir_id);
574                             let c = Const::from_anon_const(self.tcx(), local_did);
575                             ConvertedBindingKind::Equality(c.into())
576                         }
577                     },
578                     hir::TypeBindingKind::Constraint { ref bounds } => {
579                         ConvertedBindingKind::Constraint(bounds)
580                     }
581                 };
582                 ConvertedBinding {
583                     hir_id: binding.hir_id,
584                     item_name: binding.ident,
585                     kind,
586                     gen_args: binding.gen_args,
587                     span: binding.span,
588                 }
589             })
590             .collect();
591
592         assoc_bindings
593     }
594
595     pub fn create_substs_for_associated_item(
596         &self,
597         span: Span,
598         item_def_id: DefId,
599         item_segment: &hir::PathSegment<'_>,
600         parent_substs: SubstsRef<'tcx>,
601     ) -> SubstsRef<'tcx> {
602         debug!(
603             "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}",
604             span, item_def_id, item_segment
605         );
606         let (args, _) = self.create_substs_for_ast_path(
607             span,
608             item_def_id,
609             parent_substs,
610             item_segment,
611             item_segment.args(),
612             item_segment.infer_args,
613             None,
614             None,
615         );
616
617         if let Some(b) = item_segment.args().bindings.first() {
618             Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
619         }
620
621         args
622     }
623
624     /// Instantiates the path for the given trait reference, assuming that it's
625     /// bound to a valid trait type. Returns the `DefId` of the defining trait.
626     /// The type _cannot_ be a type other than a trait type.
627     ///
628     /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
629     /// are disallowed. Otherwise, they are pushed onto the vector given.
630     pub fn instantiate_mono_trait_ref(
631         &self,
632         trait_ref: &hir::TraitRef<'_>,
633         self_ty: Ty<'tcx>,
634         constness: ty::BoundConstness,
635     ) -> ty::TraitRef<'tcx> {
636         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
637
638         self.ast_path_to_mono_trait_ref(
639             trait_ref.path.span,
640             trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
641             self_ty,
642             trait_ref.path.segments.last().unwrap(),
643             true,
644             Some(constness),
645         )
646     }
647
648     fn instantiate_poly_trait_ref_inner(
649         &self,
650         hir_id: hir::HirId,
651         span: Span,
652         binding_span: Option<Span>,
653         constness: ty::BoundConstness,
654         bounds: &mut Bounds<'tcx>,
655         speculative: bool,
656         trait_ref_span: Span,
657         trait_def_id: DefId,
658         trait_segment: &hir::PathSegment<'_>,
659         args: &GenericArgs<'_>,
660         infer_args: bool,
661         self_ty: Ty<'tcx>,
662     ) -> GenericArgCountResult {
663         let (substs, arg_count) = self.create_substs_for_ast_path(
664             trait_ref_span,
665             trait_def_id,
666             &[],
667             trait_segment,
668             args,
669             infer_args,
670             Some(self_ty),
671             Some(constness),
672         );
673
674         let tcx = self.tcx();
675         let bound_vars = tcx.late_bound_vars(hir_id);
676         debug!(?bound_vars);
677
678         let assoc_bindings = self.create_assoc_bindings_for_generic_args(args);
679
680         let poly_trait_ref =
681             ty::Binder::bind_with_vars(ty::TraitRef::new(trait_def_id, substs), bound_vars);
682
683         debug!(?poly_trait_ref, ?assoc_bindings);
684         bounds.trait_bounds.push((poly_trait_ref, span, constness));
685
686         let mut dup_bindings = FxHashMap::default();
687         for binding in &assoc_bindings {
688             // Specify type to assert that error was already reported in `Err` case.
689             let _: Result<_, ErrorGuaranteed> = self.add_predicates_for_ast_type_binding(
690                 hir_id,
691                 poly_trait_ref,
692                 binding,
693                 bounds,
694                 speculative,
695                 &mut dup_bindings,
696                 binding_span.unwrap_or(binding.span),
697                 constness,
698             );
699             // Okay to ignore `Err` because of `ErrorGuaranteed` (see above).
700         }
701
702         arg_count
703     }
704
705     /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
706     /// a full trait reference. The resulting trait reference is returned. This may also generate
707     /// auxiliary bounds, which are added to `bounds`.
708     ///
709     /// Example:
710     ///
711     /// ```ignore (illustrative)
712     /// poly_trait_ref = Iterator<Item = u32>
713     /// self_ty = Foo
714     /// ```
715     ///
716     /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
717     ///
718     /// **A note on binders:** against our usual convention, there is an implied bounder around
719     /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
720     /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
721     /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
722     /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
723     /// however.
724     #[instrument(level = "debug", skip(self, span, constness, bounds, speculative))]
725     pub(crate) fn instantiate_poly_trait_ref(
726         &self,
727         trait_ref: &hir::TraitRef<'_>,
728         span: Span,
729         constness: ty::BoundConstness,
730         self_ty: Ty<'tcx>,
731         bounds: &mut Bounds<'tcx>,
732         speculative: bool,
733     ) -> GenericArgCountResult {
734         let hir_id = trait_ref.hir_ref_id;
735         let binding_span = None;
736         let trait_ref_span = trait_ref.path.span;
737         let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
738         let trait_segment = trait_ref.path.segments.last().unwrap();
739         let args = trait_segment.args();
740         let infer_args = trait_segment.infer_args;
741
742         self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
743         self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, false);
744
745         self.instantiate_poly_trait_ref_inner(
746             hir_id,
747             span,
748             binding_span,
749             constness,
750             bounds,
751             speculative,
752             trait_ref_span,
753             trait_def_id,
754             trait_segment,
755             args,
756             infer_args,
757             self_ty,
758         )
759     }
760
761     pub(crate) fn instantiate_lang_item_trait_ref(
762         &self,
763         lang_item: hir::LangItem,
764         span: Span,
765         hir_id: hir::HirId,
766         args: &GenericArgs<'_>,
767         self_ty: Ty<'tcx>,
768         bounds: &mut Bounds<'tcx>,
769     ) {
770         let binding_span = Some(span);
771         let constness = ty::BoundConstness::NotConst;
772         let speculative = false;
773         let trait_ref_span = span;
774         let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
775         let trait_segment = &hir::PathSegment::invalid();
776         let infer_args = false;
777
778         self.instantiate_poly_trait_ref_inner(
779             hir_id,
780             span,
781             binding_span,
782             constness,
783             bounds,
784             speculative,
785             trait_ref_span,
786             trait_def_id,
787             trait_segment,
788             args,
789             infer_args,
790             self_ty,
791         );
792     }
793
794     fn ast_path_to_mono_trait_ref(
795         &self,
796         span: Span,
797         trait_def_id: DefId,
798         self_ty: Ty<'tcx>,
799         trait_segment: &hir::PathSegment<'_>,
800         is_impl: bool,
801         constness: Option<ty::BoundConstness>,
802     ) -> ty::TraitRef<'tcx> {
803         let (substs, _) = self.create_substs_for_ast_trait_ref(
804             span,
805             trait_def_id,
806             self_ty,
807             trait_segment,
808             is_impl,
809             constness,
810         );
811         if let Some(b) = trait_segment.args().bindings.first() {
812             Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
813         }
814         ty::TraitRef::new(trait_def_id, substs)
815     }
816
817     #[instrument(level = "debug", skip(self, span))]
818     fn create_substs_for_ast_trait_ref<'a>(
819         &self,
820         span: Span,
821         trait_def_id: DefId,
822         self_ty: Ty<'tcx>,
823         trait_segment: &'a hir::PathSegment<'a>,
824         is_impl: bool,
825         constness: Option<ty::BoundConstness>,
826     ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
827         self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
828
829         self.create_substs_for_ast_path(
830             span,
831             trait_def_id,
832             &[],
833             trait_segment,
834             trait_segment.args(),
835             trait_segment.infer_args,
836             Some(self_ty),
837             constness,
838         )
839     }
840
841     fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
842         self.tcx()
843             .associated_items(trait_def_id)
844             .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
845             .is_some()
846     }
847     fn trait_defines_associated_const_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
848         self.tcx()
849             .associated_items(trait_def_id)
850             .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Const, trait_def_id)
851             .is_some()
852     }
853
854     // Sets `implicitly_sized` to true on `Bounds` if necessary
855     pub(crate) fn add_implicitly_sized<'hir>(
856         &self,
857         bounds: &mut Bounds<'hir>,
858         ast_bounds: &'hir [hir::GenericBound<'hir>],
859         self_ty_where_predicates: Option<(hir::HirId, &'hir [hir::WherePredicate<'hir>])>,
860         span: Span,
861     ) {
862         let tcx = self.tcx();
863
864         // Try to find an unbound in bounds.
865         let mut unbound = None;
866         let mut search_bounds = |ast_bounds: &'hir [hir::GenericBound<'hir>]| {
867             for ab in ast_bounds {
868                 if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab {
869                     if unbound.is_none() {
870                         unbound = Some(&ptr.trait_ref);
871                     } else {
872                         tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span });
873                     }
874                 }
875             }
876         };
877         search_bounds(ast_bounds);
878         if let Some((self_ty, where_clause)) = self_ty_where_predicates {
879             let self_ty_def_id = tcx.hir().local_def_id(self_ty).to_def_id();
880             for clause in where_clause {
881                 if let hir::WherePredicate::BoundPredicate(pred) = clause {
882                     if pred.is_param_bound(self_ty_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
967                         .region_bounds
968                         .push((ty::Binder::bind_with_vars(region, bound_vars), lifetime.span));
969                 }
970             }
971         }
972     }
973
974     /// Translates a list of bounds from the HIR into the `Bounds` data structure.
975     /// The self-type for the bounds is given by `param_ty`.
976     ///
977     /// Example:
978     ///
979     /// ```ignore (illustrative)
980     /// fn foo<T: Bar + Baz>() { }
981     /// //     ^  ^^^^^^^^^ ast_bounds
982     /// //     param_ty
983     /// ```
984     ///
985     /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
986     /// considered `Sized` unless there is an explicit `?Sized` bound.  This would be true in the
987     /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
988     ///
989     /// `span` should be the declaration size of the parameter.
990     pub(crate) fn compute_bounds(
991         &self,
992         param_ty: Ty<'tcx>,
993         ast_bounds: &[hir::GenericBound<'_>],
994     ) -> Bounds<'tcx> {
995         self.compute_bounds_inner(param_ty, ast_bounds)
996     }
997
998     /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type
999     /// named `assoc_name` into ty::Bounds. Ignore the rest.
1000     pub(crate) fn compute_bounds_that_match_assoc_type(
1001         &self,
1002         param_ty: Ty<'tcx>,
1003         ast_bounds: &[hir::GenericBound<'_>],
1004         assoc_name: Ident,
1005     ) -> Bounds<'tcx> {
1006         let mut result = Vec::new();
1007
1008         for ast_bound in ast_bounds {
1009             if let Some(trait_ref) = ast_bound.trait_ref()
1010                 && let Some(trait_did) = trait_ref.trait_def_id()
1011                 && self.tcx().trait_may_define_assoc_type(trait_did, assoc_name)
1012             {
1013                 result.push(ast_bound.clone());
1014             }
1015         }
1016
1017         self.compute_bounds_inner(param_ty, &result)
1018     }
1019
1020     fn compute_bounds_inner(
1021         &self,
1022         param_ty: Ty<'tcx>,
1023         ast_bounds: &[hir::GenericBound<'_>],
1024     ) -> Bounds<'tcx> {
1025         let mut bounds = Bounds::default();
1026
1027         self.add_bounds(param_ty, ast_bounds.iter(), &mut bounds, ty::List::empty());
1028         debug!(?bounds);
1029
1030         bounds
1031     }
1032
1033     /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1034     /// onto `bounds`.
1035     ///
1036     /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1037     /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1038     /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1039     #[instrument(level = "debug", skip(self, bounds, speculative, dup_bindings, path_span))]
1040     fn add_predicates_for_ast_type_binding(
1041         &self,
1042         hir_ref_id: hir::HirId,
1043         trait_ref: ty::PolyTraitRef<'tcx>,
1044         binding: &ConvertedBinding<'_, 'tcx>,
1045         bounds: &mut Bounds<'tcx>,
1046         speculative: bool,
1047         dup_bindings: &mut FxHashMap<DefId, Span>,
1048         path_span: Span,
1049         constness: ty::BoundConstness,
1050     ) -> Result<(), ErrorGuaranteed> {
1051         // Given something like `U: SomeTrait<T = X>`, we want to produce a
1052         // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1053         // subtle in the event that `T` is defined in a supertrait of
1054         // `SomeTrait`, because in that case we need to upcast.
1055         //
1056         // That is, consider this case:
1057         //
1058         // ```
1059         // trait SubTrait: SuperTrait<i32> { }
1060         // trait SuperTrait<A> { type T; }
1061         //
1062         // ... B: SubTrait<T = foo> ...
1063         // ```
1064         //
1065         // We want to produce `<B as SuperTrait<i32>>::T == foo`.
1066
1067         let tcx = self.tcx();
1068
1069         let candidate =
1070             if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1071                 // Simple case: X is defined in the current trait.
1072                 trait_ref
1073             } else {
1074                 // Otherwise, we have to walk through the supertraits to find
1075                 // those that do.
1076                 self.one_bound_for_assoc_type(
1077                     || traits::supertraits(tcx, trait_ref),
1078                     || trait_ref.print_only_trait_path().to_string(),
1079                     binding.item_name,
1080                     path_span,
1081                     || match binding.kind {
1082                         ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1083                         _ => None,
1084                     },
1085                 )?
1086             };
1087
1088         let (assoc_ident, def_scope) =
1089             tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1090
1091         // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1092         // of calling `filter_by_name_and_kind`.
1093         let find_item_of_kind = |kind| {
1094             tcx.associated_items(candidate.def_id())
1095                 .filter_by_name_unhygienic(assoc_ident.name)
1096                 .find(|i| i.kind == kind && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident)
1097         };
1098         let assoc_item = find_item_of_kind(ty::AssocKind::Type)
1099             .or_else(|| find_item_of_kind(ty::AssocKind::Const))
1100             .expect("missing associated type");
1101
1102         if !assoc_item.visibility(tcx).is_accessible_from(def_scope, tcx) {
1103             tcx.sess
1104                 .struct_span_err(
1105                     binding.span,
1106                     &format!("{} `{}` is private", assoc_item.kind, binding.item_name),
1107                 )
1108                 .span_label(binding.span, &format!("private {}", assoc_item.kind))
1109                 .emit();
1110         }
1111         tcx.check_stability(assoc_item.def_id, Some(hir_ref_id), binding.span, None);
1112
1113         if !speculative {
1114             dup_bindings
1115                 .entry(assoc_item.def_id)
1116                 .and_modify(|prev_span| {
1117                     self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified {
1118                         span: binding.span,
1119                         prev_span: *prev_span,
1120                         item_name: binding.item_name,
1121                         def_path: tcx.def_path_str(assoc_item.container_id(tcx)),
1122                     });
1123                 })
1124                 .or_insert(binding.span);
1125         }
1126
1127         // Include substitutions for generic parameters of associated types
1128         let projection_ty = candidate.map_bound(|trait_ref| {
1129             let ident = Ident::new(assoc_item.name, binding.item_name.span);
1130             let item_segment = hir::PathSegment {
1131                 ident,
1132                 hir_id: binding.hir_id,
1133                 res: Res::Err,
1134                 args: Some(binding.gen_args),
1135                 infer_args: false,
1136             };
1137
1138             let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item(
1139                 path_span,
1140                 assoc_item.def_id,
1141                 &item_segment,
1142                 trait_ref.substs,
1143             );
1144
1145             debug!(?substs_trait_ref_and_assoc_item);
1146
1147             ty::ProjectionTy {
1148                 item_def_id: assoc_item.def_id,
1149                 substs: substs_trait_ref_and_assoc_item,
1150             }
1151         });
1152
1153         if !speculative {
1154             // Find any late-bound regions declared in `ty` that are not
1155             // declared in the trait-ref or assoc_item. These are not well-formed.
1156             //
1157             // Example:
1158             //
1159             //     for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1160             //     for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1161             if let ConvertedBindingKind::Equality(ty) = binding.kind {
1162                 let late_bound_in_trait_ref =
1163                     tcx.collect_constrained_late_bound_regions(&projection_ty);
1164                 let late_bound_in_ty =
1165                     tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty));
1166                 debug!(?late_bound_in_trait_ref);
1167                 debug!(?late_bound_in_ty);
1168
1169                 // FIXME: point at the type params that don't have appropriate lifetimes:
1170                 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1171                 //                         ----  ----     ^^^^^^^
1172                 self.validate_late_bound_regions(
1173                     late_bound_in_trait_ref,
1174                     late_bound_in_ty,
1175                     |br_name| {
1176                         struct_span_err!(
1177                             tcx.sess,
1178                             binding.span,
1179                             E0582,
1180                             "binding for associated type `{}` references {}, \
1181                              which does not appear in the trait input types",
1182                             binding.item_name,
1183                             br_name
1184                         )
1185                     },
1186                 );
1187             }
1188         }
1189
1190         match binding.kind {
1191             ConvertedBindingKind::Equality(mut term) => {
1192                 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1193                 // the "projection predicate" for:
1194                 //
1195                 // `<T as Iterator>::Item = u32`
1196                 let assoc_item_def_id = projection_ty.skip_binder().item_def_id;
1197                 let def_kind = tcx.def_kind(assoc_item_def_id);
1198                 match (def_kind, term.unpack()) {
1199                     (hir::def::DefKind::AssocTy, ty::TermKind::Ty(_))
1200                     | (hir::def::DefKind::AssocConst, ty::TermKind::Const(_)) => (),
1201                     (_, _) => {
1202                         let got = if let Some(_) = term.ty() { "type" } else { "constant" };
1203                         let expected = def_kind.descr(assoc_item_def_id);
1204                         tcx.sess
1205                             .struct_span_err(
1206                                 binding.span,
1207                                 &format!("expected {expected} bound, found {got}"),
1208                             )
1209                             .span_note(
1210                                 tcx.def_span(assoc_item_def_id),
1211                                 &format!("{expected} defined here"),
1212                             )
1213                             .emit();
1214                         term = match def_kind {
1215                             hir::def::DefKind::AssocTy => tcx.ty_error().into(),
1216                             hir::def::DefKind::AssocConst => tcx
1217                                 .const_error(
1218                                     tcx.bound_type_of(assoc_item_def_id)
1219                                         .subst(tcx, projection_ty.skip_binder().substs),
1220                                 )
1221                                 .into(),
1222                             _ => unreachable!(),
1223                         };
1224                     }
1225                 }
1226                 bounds.projection_bounds.push((
1227                     projection_ty.map_bound(|projection_ty| ty::ProjectionPredicate {
1228                         projection_ty,
1229                         term: term,
1230                     }),
1231                     binding.span,
1232                 ));
1233             }
1234             ConvertedBindingKind::Constraint(ast_bounds) => {
1235                 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1236                 //
1237                 // `<T as Iterator>::Item: Debug`
1238                 //
1239                 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1240                 // parameter to have a skipped binder.
1241                 let param_ty = tcx.mk_ty(ty::Projection(projection_ty.skip_binder()));
1242                 self.add_bounds(param_ty, ast_bounds.iter(), bounds, candidate.bound_vars());
1243             }
1244         }
1245         Ok(())
1246     }
1247
1248     fn ast_path_to_ty(
1249         &self,
1250         span: Span,
1251         did: DefId,
1252         item_segment: &hir::PathSegment<'_>,
1253     ) -> Ty<'tcx> {
1254         let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1255         self.normalize_ty(
1256             span,
1257             EarlyBinder(self.tcx().at(span).type_of(did)).subst(self.tcx(), substs),
1258         )
1259     }
1260
1261     fn conv_object_ty_poly_trait_ref(
1262         &self,
1263         span: Span,
1264         trait_bounds: &[hir::PolyTraitRef<'_>],
1265         lifetime: &hir::Lifetime,
1266         borrowed: bool,
1267         representation: DynKind,
1268     ) -> Ty<'tcx> {
1269         let tcx = self.tcx();
1270
1271         let mut bounds = Bounds::default();
1272         let mut potential_assoc_types = Vec::new();
1273         let dummy_self = self.tcx().types.trait_object_dummy_self;
1274         for trait_bound in trait_bounds.iter().rev() {
1275             if let GenericArgCountResult {
1276                 correct:
1277                     Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1278                 ..
1279             } = self.instantiate_poly_trait_ref(
1280                 &trait_bound.trait_ref,
1281                 trait_bound.span,
1282                 ty::BoundConstness::NotConst,
1283                 dummy_self,
1284                 &mut bounds,
1285                 false,
1286             ) {
1287                 potential_assoc_types.extend(cur_potential_assoc_types);
1288             }
1289         }
1290
1291         // Expand trait aliases recursively and check that only one regular (non-auto) trait
1292         // is used and no 'maybe' bounds are used.
1293         let expanded_traits =
1294             traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1295         let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) = expanded_traits
1296             .filter(|i| i.trait_ref().self_ty().skip_binder() == dummy_self)
1297             .partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1298         if regular_traits.len() > 1 {
1299             let first_trait = &regular_traits[0];
1300             let additional_trait = &regular_traits[1];
1301             let mut err = struct_span_err!(
1302                 tcx.sess,
1303                 additional_trait.bottom().1,
1304                 E0225,
1305                 "only auto traits can be used as additional traits in a trait object"
1306             );
1307             additional_trait.label_with_exp_info(
1308                 &mut err,
1309                 "additional non-auto trait",
1310                 "additional use",
1311             );
1312             first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1313             err.help(&format!(
1314                 "consider creating a new trait with all of these as supertraits and using that \
1315                  trait here instead: `trait NewTrait: {} {{}}`",
1316                 regular_traits
1317                     .iter()
1318                     .map(|t| t.trait_ref().print_only_trait_path().to_string())
1319                     .collect::<Vec<_>>()
1320                     .join(" + "),
1321             ));
1322             err.note(
1323                 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1324                  for more information on them, visit \
1325                  <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1326             );
1327             err.emit();
1328         }
1329
1330         if regular_traits.is_empty() && auto_traits.is_empty() {
1331             let trait_alias_span = bounds
1332                 .trait_bounds
1333                 .iter()
1334                 .map(|&(trait_ref, _, _)| trait_ref.def_id())
1335                 .find(|&trait_ref| tcx.is_trait_alias(trait_ref))
1336                 .map(|trait_ref| tcx.def_span(trait_ref));
1337             tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span, trait_alias_span });
1338             return tcx.ty_error();
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                 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();
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::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::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, _) = 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
1915         // Find the type of the associated item, and the trait where the associated
1916         // item is declared.
1917         let bound = match (&qself_ty.kind(), qself_res) {
1918             (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1919                 // `Self` in an impl of a trait -- we have a concrete self type and a
1920                 // trait reference.
1921                 let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) else {
1922                     // A cycle error occurred, most likely.
1923                     let guar = tcx.sess.delay_span_bug(span, "expected cycle error");
1924                     return Err(guar);
1925                 };
1926
1927                 self.one_bound_for_assoc_type(
1928                     || traits::supertraits(tcx, ty::Binder::dummy(trait_ref)),
1929                     || "Self".to_string(),
1930                     assoc_ident,
1931                     span,
1932                     || None,
1933                 )?
1934             }
1935             (
1936                 &ty::Param(_),
1937                 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
1938             ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
1939             _ => {
1940                 let reported = if variant_resolution.is_some() {
1941                     // Variant in type position
1942                     let msg = format!("expected type, found variant `{}`", assoc_ident);
1943                     tcx.sess.span_err(span, &msg)
1944                 } else if qself_ty.is_enum() {
1945                     let mut err = struct_span_err!(
1946                         tcx.sess,
1947                         assoc_ident.span,
1948                         E0599,
1949                         "no variant named `{}` found for enum `{}`",
1950                         assoc_ident,
1951                         qself_ty,
1952                     );
1953
1954                     let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1955                     if let Some(suggested_name) = find_best_match_for_name(
1956                         &adt_def
1957                             .variants()
1958                             .iter()
1959                             .map(|variant| variant.name)
1960                             .collect::<Vec<Symbol>>(),
1961                         assoc_ident.name,
1962                         None,
1963                     ) {
1964                         err.span_suggestion(
1965                             assoc_ident.span,
1966                             "there is a variant with a similar name",
1967                             suggested_name,
1968                             Applicability::MaybeIncorrect,
1969                         );
1970                     } else {
1971                         err.span_label(
1972                             assoc_ident.span,
1973                             format!("variant not found in `{}`", qself_ty),
1974                         );
1975                     }
1976
1977                     if let Some(sp) = tcx.hir().span_if_local(adt_def.did()) {
1978                         err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1979                     }
1980
1981                     err.emit()
1982                 } else if let Some(reported) = qself_ty.error_reported() {
1983                     reported
1984                 } else {
1985                     // Don't print `TyErr` to the user.
1986                     self.report_ambiguous_associated_type(
1987                         span,
1988                         &qself_ty.to_string(),
1989                         "Trait",
1990                         assoc_ident.name,
1991                     )
1992                 };
1993                 return Err(reported);
1994             }
1995         };
1996
1997         let trait_did = bound.def_id();
1998         let (assoc_ident, def_scope) =
1999             tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
2000
2001         // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
2002         // of calling `filter_by_name_and_kind`.
2003         let item = tcx.associated_items(trait_did).in_definition_order().find(|i| {
2004             i.kind.namespace() == Namespace::TypeNS
2005                 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
2006         });
2007         // Assume that if it's not matched, there must be a const defined with the same name
2008         // but it was used in a type position.
2009         let Some(item) = item else {
2010             let msg = format!("found associated const `{assoc_ident}` when type was expected");
2011             let guar = tcx.sess.struct_span_err(span, &msg).emit();
2012             return Err(guar);
2013         };
2014
2015         let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
2016         let ty = self.normalize_ty(span, ty);
2017
2018         let kind = DefKind::AssocTy;
2019         if !item.visibility(tcx).is_accessible_from(def_scope, tcx) {
2020             let kind = kind.descr(item.def_id);
2021             let msg = format!("{} `{}` is private", kind, assoc_ident);
2022             tcx.sess
2023                 .struct_span_err(span, &msg)
2024                 .span_label(span, &format!("private {}", kind))
2025                 .emit();
2026         }
2027         tcx.check_stability(item.def_id, Some(hir_ref_id), span, None);
2028
2029         if let Some(variant_def_id) = variant_resolution {
2030             tcx.struct_span_lint_hir(
2031                 AMBIGUOUS_ASSOCIATED_ITEMS,
2032                 hir_ref_id,
2033                 span,
2034                 "ambiguous associated item",
2035                 |lint| {
2036                     let mut could_refer_to = |kind: DefKind, def_id, also| {
2037                         let note_msg = format!(
2038                             "`{}` could{} refer to the {} defined here",
2039                             assoc_ident,
2040                             also,
2041                             kind.descr(def_id)
2042                         );
2043                         lint.span_note(tcx.def_span(def_id), &note_msg);
2044                     };
2045
2046                     could_refer_to(DefKind::Variant, variant_def_id, "");
2047                     could_refer_to(kind, item.def_id, " also");
2048
2049                     lint.span_suggestion(
2050                         span,
2051                         "use fully-qualified syntax",
2052                         format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2053                         Applicability::MachineApplicable,
2054                     );
2055
2056                     lint
2057                 },
2058             );
2059         }
2060         Ok((ty, kind, item.def_id))
2061     }
2062
2063     fn qpath_to_ty(
2064         &self,
2065         span: Span,
2066         opt_self_ty: Option<Ty<'tcx>>,
2067         item_def_id: DefId,
2068         trait_segment: &hir::PathSegment<'_>,
2069         item_segment: &hir::PathSegment<'_>,
2070         constness: ty::BoundConstness,
2071     ) -> Ty<'tcx> {
2072         let tcx = self.tcx();
2073
2074         let trait_def_id = tcx.parent(item_def_id);
2075
2076         debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2077
2078         let Some(self_ty) = opt_self_ty else {
2079             let path_str = tcx.def_path_str(trait_def_id);
2080
2081             let def_id = self.item_def_id();
2082
2083             debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2084
2085             let parent_def_id = def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
2086                 .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id());
2087
2088             debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2089
2090             // If the trait in segment is the same as the trait defining the item,
2091             // use the `<Self as ..>` syntax in the error.
2092             let is_part_of_self_trait_constraints = def_id == trait_def_id;
2093             let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2094
2095             let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2096                 "Self"
2097             } else {
2098                 "Type"
2099             };
2100
2101             self.report_ambiguous_associated_type(
2102                 span,
2103                 type_name,
2104                 &path_str,
2105                 item_segment.ident.name,
2106             );
2107             return tcx.ty_error();
2108         };
2109
2110         debug!("qpath_to_ty: self_type={:?}", self_ty);
2111
2112         let trait_ref = self.ast_path_to_mono_trait_ref(
2113             span,
2114             trait_def_id,
2115             self_ty,
2116             trait_segment,
2117             false,
2118             Some(constness),
2119         );
2120
2121         let item_substs = self.create_substs_for_associated_item(
2122             span,
2123             item_def_id,
2124             item_segment,
2125             trait_ref.substs,
2126         );
2127
2128         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2129
2130         self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2131     }
2132
2133     pub fn prohibit_generics<'a>(
2134         &self,
2135         segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
2136         extend: impl Fn(&mut Diagnostic),
2137     ) -> bool {
2138         let args = segments.clone().flat_map(|segment| segment.args().args);
2139
2140         let (lt, ty, ct, inf) =
2141             args.clone().fold((false, false, false, false), |(lt, ty, ct, inf), arg| match arg {
2142                 hir::GenericArg::Lifetime(_) => (true, ty, ct, inf),
2143                 hir::GenericArg::Type(_) => (lt, true, ct, inf),
2144                 hir::GenericArg::Const(_) => (lt, ty, true, inf),
2145                 hir::GenericArg::Infer(_) => (lt, ty, ct, true),
2146             });
2147         let mut emitted = false;
2148         if lt || ty || ct || inf {
2149             let types_and_spans: Vec<_> = segments
2150                 .clone()
2151                 .flat_map(|segment| {
2152                     if segment.args().args.is_empty() {
2153                         None
2154                     } else {
2155                         Some((
2156                             match segment.res {
2157                                 Res::PrimTy(ty) => format!("{} `{}`", segment.res.descr(), ty.name()),
2158                                 Res::Def(_, def_id)
2159                                 if let Some(name) = self.tcx().opt_item_name(def_id) => {
2160                                     format!("{} `{name}`", segment.res.descr())
2161                                 }
2162                                 Res::Err => "this type".to_string(),
2163                                 _ => segment.res.descr().to_string(),
2164                             },
2165                             segment.ident.span,
2166                         ))
2167                     }
2168                 })
2169                 .collect();
2170             let this_type = match &types_and_spans[..] {
2171                 [.., _, (last, _)] => format!(
2172                     "{} and {last}",
2173                     types_and_spans[..types_and_spans.len() - 1]
2174                         .iter()
2175                         .map(|(x, _)| x.as_str())
2176                         .intersperse(&", ")
2177                         .collect::<String>()
2178                 ),
2179                 [(only, _)] => only.to_string(),
2180                 [] => "this type".to_string(),
2181             };
2182
2183             let arg_spans: Vec<Span> = args.map(|arg| arg.span()).collect();
2184
2185             let mut kinds = Vec::with_capacity(4);
2186             if lt {
2187                 kinds.push("lifetime");
2188             }
2189             if ty {
2190                 kinds.push("type");
2191             }
2192             if ct {
2193                 kinds.push("const");
2194             }
2195             if inf {
2196                 kinds.push("generic");
2197             }
2198             let (kind, s) = match kinds[..] {
2199                 [.., _, last] => (
2200                     format!(
2201                         "{} and {last}",
2202                         kinds[..kinds.len() - 1]
2203                             .iter()
2204                             .map(|&x| x)
2205                             .intersperse(", ")
2206                             .collect::<String>()
2207                     ),
2208                     "s",
2209                 ),
2210                 [only] => (format!("{only}"), ""),
2211                 [] => unreachable!(),
2212             };
2213             let last_span = *arg_spans.last().unwrap();
2214             let span: MultiSpan = arg_spans.into();
2215             let mut err = struct_span_err!(
2216                 self.tcx().sess,
2217                 span,
2218                 E0109,
2219                 "{kind} arguments are not allowed on {this_type}",
2220             );
2221             err.span_label(last_span, format!("{kind} argument{s} not allowed"));
2222             for (what, span) in types_and_spans {
2223                 err.span_label(span, format!("not allowed on {what}"));
2224             }
2225             extend(&mut err);
2226             err.emit();
2227             emitted = true;
2228         }
2229
2230         for segment in segments {
2231             // Only emit the first error to avoid overloading the user with error messages.
2232             if let Some(b) = segment.args().bindings.first() {
2233                 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
2234                 return true;
2235             }
2236         }
2237         emitted
2238     }
2239
2240     // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2241     pub fn def_ids_for_value_path_segments(
2242         &self,
2243         segments: &[hir::PathSegment<'_>],
2244         self_ty: Option<Ty<'tcx>>,
2245         kind: DefKind,
2246         def_id: DefId,
2247     ) -> Vec<PathSeg> {
2248         // We need to extract the type parameters supplied by the user in
2249         // the path `path`. Due to the current setup, this is a bit of a
2250         // tricky-process; the problem is that resolve only tells us the
2251         // end-point of the path resolution, and not the intermediate steps.
2252         // Luckily, we can (at least for now) deduce the intermediate steps
2253         // just from the end-point.
2254         //
2255         // There are basically five cases to consider:
2256         //
2257         // 1. Reference to a constructor of a struct:
2258         //
2259         //        struct Foo<T>(...)
2260         //
2261         //    In this case, the parameters are declared in the type space.
2262         //
2263         // 2. Reference to a constructor of an enum variant:
2264         //
2265         //        enum E<T> { Foo(...) }
2266         //
2267         //    In this case, the parameters are defined in the type space,
2268         //    but may be specified either on the type or the variant.
2269         //
2270         // 3. Reference to a fn item or a free constant:
2271         //
2272         //        fn foo<T>() { }
2273         //
2274         //    In this case, the path will again always have the form
2275         //    `a::b::foo::<T>` where only the final segment should have
2276         //    type parameters. However, in this case, those parameters are
2277         //    declared on a value, and hence are in the `FnSpace`.
2278         //
2279         // 4. Reference to a method or an associated constant:
2280         //
2281         //        impl<A> SomeStruct<A> {
2282         //            fn foo<B>(...)
2283         //        }
2284         //
2285         //    Here we can have a path like
2286         //    `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2287         //    may appear in two places. The penultimate segment,
2288         //    `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2289         //    final segment, `foo::<B>` contains parameters in fn space.
2290         //
2291         // The first step then is to categorize the segments appropriately.
2292
2293         let tcx = self.tcx();
2294
2295         assert!(!segments.is_empty());
2296         let last = segments.len() - 1;
2297
2298         let mut path_segs = vec![];
2299
2300         match kind {
2301             // Case 1. Reference to a struct constructor.
2302             DefKind::Ctor(CtorOf::Struct, ..) => {
2303                 // Everything but the final segment should have no
2304                 // parameters at all.
2305                 let generics = tcx.generics_of(def_id);
2306                 // Variant and struct constructors use the
2307                 // generics of their parent type definition.
2308                 let generics_def_id = generics.parent.unwrap_or(def_id);
2309                 path_segs.push(PathSeg(generics_def_id, last));
2310             }
2311
2312             // Case 2. Reference to a variant constructor.
2313             DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2314                 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2315                 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2316                     debug_assert!(adt_def.is_enum());
2317                     (adt_def.did(), last)
2318                 } else if last >= 1 && segments[last - 1].args.is_some() {
2319                     // Everything but the penultimate segment should have no
2320                     // parameters at all.
2321                     let mut def_id = def_id;
2322
2323                     // `DefKind::Ctor` -> `DefKind::Variant`
2324                     if let DefKind::Ctor(..) = kind {
2325                         def_id = tcx.parent(def_id);
2326                     }
2327
2328                     // `DefKind::Variant` -> `DefKind::Enum`
2329                     let enum_def_id = tcx.parent(def_id);
2330                     (enum_def_id, last - 1)
2331                 } else {
2332                     // FIXME: lint here recommending `Enum::<...>::Variant` form
2333                     // instead of `Enum::Variant::<...>` form.
2334
2335                     // Everything but the final segment should have no
2336                     // parameters at all.
2337                     let generics = tcx.generics_of(def_id);
2338                     // Variant and struct constructors use the
2339                     // generics of their parent type definition.
2340                     (generics.parent.unwrap_or(def_id), last)
2341                 };
2342                 path_segs.push(PathSeg(generics_def_id, index));
2343             }
2344
2345             // Case 3. Reference to a top-level value.
2346             DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static(_) => {
2347                 path_segs.push(PathSeg(def_id, last));
2348             }
2349
2350             // Case 4. Reference to a method or associated const.
2351             DefKind::AssocFn | DefKind::AssocConst => {
2352                 if segments.len() >= 2 {
2353                     let generics = tcx.generics_of(def_id);
2354                     path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2355                 }
2356                 path_segs.push(PathSeg(def_id, last));
2357             }
2358
2359             kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2360         }
2361
2362         debug!("path_segs = {:?}", path_segs);
2363
2364         path_segs
2365     }
2366
2367     // Check a type `Path` and convert it to a `Ty`.
2368     pub fn res_to_ty(
2369         &self,
2370         opt_self_ty: Option<Ty<'tcx>>,
2371         path: &hir::Path<'_>,
2372         permit_variants: bool,
2373     ) -> Ty<'tcx> {
2374         let tcx = self.tcx();
2375
2376         debug!(
2377             "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2378             path.res, opt_self_ty, path.segments
2379         );
2380
2381         let span = path.span;
2382         match path.res {
2383             Res::Def(DefKind::OpaqueTy | DefKind::ImplTraitPlaceholder, did) => {
2384                 // Check for desugared `impl Trait`.
2385                 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2386                 let item_segment = path.segments.split_last().unwrap();
2387                 self.prohibit_generics(item_segment.1.iter(), |err| {
2388                     err.note("`impl Trait` types can't have type parameters");
2389                 });
2390                 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2391                 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2392             }
2393             Res::Def(
2394                 DefKind::Enum
2395                 | DefKind::TyAlias
2396                 | DefKind::Struct
2397                 | DefKind::Union
2398                 | DefKind::ForeignTy,
2399                 did,
2400             ) => {
2401                 assert_eq!(opt_self_ty, None);
2402                 self.prohibit_generics(path.segments.split_last().unwrap().1.iter(), |_| {});
2403                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2404             }
2405             Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2406                 // Convert "variant type" as if it were a real type.
2407                 // The resulting `Ty` is type of the variant's enum for now.
2408                 assert_eq!(opt_self_ty, None);
2409
2410                 let path_segs =
2411                     self.def_ids_for_value_path_segments(path.segments, None, kind, def_id);
2412                 let generic_segs: FxHashSet<_> =
2413                     path_segs.iter().map(|PathSeg(_, index)| index).collect();
2414                 self.prohibit_generics(
2415                     path.segments.iter().enumerate().filter_map(|(index, seg)| {
2416                         if !generic_segs.contains(&index) { Some(seg) } else { None }
2417                     }),
2418                     |err| {
2419                         err.note("enum variants can't have type parameters");
2420                     },
2421                 );
2422
2423                 let PathSeg(def_id, index) = path_segs.last().unwrap();
2424                 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2425             }
2426             Res::Def(DefKind::TyParam, def_id) => {
2427                 assert_eq!(opt_self_ty, None);
2428                 self.prohibit_generics(path.segments.iter(), |err| {
2429                     if let Some(span) = tcx.def_ident_span(def_id) {
2430                         let name = tcx.item_name(def_id);
2431                         err.span_note(span, &format!("type parameter `{name}` defined here"));
2432                     }
2433                 });
2434
2435                 let def_id = def_id.expect_local();
2436                 let item_def_id = tcx.hir().ty_param_owner(def_id);
2437                 let generics = tcx.generics_of(item_def_id);
2438                 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2439                 tcx.mk_ty_param(index, tcx.hir().ty_param_name(def_id))
2440             }
2441             Res::SelfTyParam { .. } => {
2442                 // `Self` in trait or type alias.
2443                 assert_eq!(opt_self_ty, None);
2444                 self.prohibit_generics(path.segments.iter(), |err| {
2445                     if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments[..] {
2446                         err.span_suggestion_verbose(
2447                             ident.span.shrink_to_hi().to(args.span_ext),
2448                             "the `Self` type doesn't accept type parameters",
2449                             "",
2450                             Applicability::MaybeIncorrect,
2451                         );
2452                     }
2453                 });
2454                 tcx.types.self_param
2455             }
2456             Res::SelfTyAlias { alias_to: def_id, forbid_generic, .. } => {
2457                 // `Self` in impl (we know the concrete type).
2458                 assert_eq!(opt_self_ty, None);
2459                 // Try to evaluate any array length constants.
2460                 let ty = tcx.at(span).type_of(def_id);
2461                 let span_of_impl = tcx.span_of_impl(def_id);
2462                 self.prohibit_generics(path.segments.iter(), |err| {
2463                     let def_id = match *ty.kind() {
2464                         ty::Adt(self_def, _) => self_def.did(),
2465                         _ => return,
2466                     };
2467
2468                     let type_name = tcx.item_name(def_id);
2469                     let span_of_ty = tcx.def_ident_span(def_id);
2470                     let generics = tcx.generics_of(def_id).count();
2471
2472                     let msg = format!("`Self` is of type `{ty}`");
2473                     if let (Ok(i_sp), Some(t_sp)) = (span_of_impl, span_of_ty) {
2474                         let mut span: MultiSpan = vec![t_sp].into();
2475                         span.push_span_label(
2476                             i_sp,
2477                             &format!("`Self` is on type `{type_name}` in this `impl`"),
2478                         );
2479                         let mut postfix = "";
2480                         if generics == 0 {
2481                             postfix = ", which doesn't have generic parameters";
2482                         }
2483                         span.push_span_label(
2484                             t_sp,
2485                             &format!("`Self` corresponds to this type{postfix}"),
2486                         );
2487                         err.span_note(span, &msg);
2488                     } else {
2489                         err.note(&msg);
2490                     }
2491                     for segment in path.segments {
2492                         if let Some(args) = segment.args && segment.ident.name == kw::SelfUpper {
2493                             if generics == 0 {
2494                                 // FIXME(estebank): we could also verify that the arguments being
2495                                 // work for the `enum`, instead of just looking if it takes *any*.
2496                                 err.span_suggestion_verbose(
2497                                     segment.ident.span.shrink_to_hi().to(args.span_ext),
2498                                     "the `Self` type doesn't accept type parameters",
2499                                     "",
2500                                     Applicability::MachineApplicable,
2501                                 );
2502                                 return;
2503                             } else {
2504                                 err.span_suggestion_verbose(
2505                                     segment.ident.span,
2506                                     format!(
2507                                         "the `Self` type doesn't accept type parameters, use the \
2508                                         concrete type's name `{type_name}` instead if you want to \
2509                                         specify its type parameters"
2510                                     ),
2511                                     type_name,
2512                                     Applicability::MaybeIncorrect,
2513                                 );
2514                             }
2515                         }
2516                     }
2517                 });
2518                 // HACK(min_const_generics): Forbid generic `Self` types
2519                 // here as we can't easily do that during nameres.
2520                 //
2521                 // We do this before normalization as we otherwise allow
2522                 // ```rust
2523                 // trait AlwaysApplicable { type Assoc; }
2524                 // impl<T: ?Sized> AlwaysApplicable for T { type Assoc = usize; }
2525                 //
2526                 // trait BindsParam<T> {
2527                 //     type ArrayTy;
2528                 // }
2529                 // impl<T> BindsParam<T> for <T as AlwaysApplicable>::Assoc {
2530                 //    type ArrayTy = [u8; Self::MAX];
2531                 // }
2532                 // ```
2533                 // Note that the normalization happens in the param env of
2534                 // the anon const, which is empty. This is why the
2535                 // `AlwaysApplicable` impl needs a `T: ?Sized` bound for
2536                 // this to compile if we were to normalize here.
2537                 if forbid_generic && ty.needs_subst() {
2538                     let mut err = tcx.sess.struct_span_err(
2539                         path.span,
2540                         "generic `Self` types are currently not permitted in anonymous constants",
2541                     );
2542                     if let Some(hir::Node::Item(&hir::Item {
2543                         kind: hir::ItemKind::Impl(ref impl_),
2544                         ..
2545                     })) = tcx.hir().get_if_local(def_id)
2546                     {
2547                         err.span_note(impl_.self_ty.span, "not a concrete type");
2548                     }
2549                     err.emit();
2550                     tcx.ty_error()
2551                 } else {
2552                     self.normalize_ty(span, ty)
2553                 }
2554             }
2555             Res::Def(DefKind::AssocTy, def_id) => {
2556                 debug_assert!(path.segments.len() >= 2);
2557                 self.prohibit_generics(path.segments[..path.segments.len() - 2].iter(), |_| {});
2558                 // HACK: until we support `<Type as ~const Trait>`, assume all of them are.
2559                 let constness = if tcx.has_attr(tcx.parent(def_id), sym::const_trait) {
2560                     ty::BoundConstness::ConstIfConst
2561                 } else {
2562                     ty::BoundConstness::NotConst
2563                 };
2564                 self.qpath_to_ty(
2565                     span,
2566                     opt_self_ty,
2567                     def_id,
2568                     &path.segments[path.segments.len() - 2],
2569                     path.segments.last().unwrap(),
2570                     constness,
2571                 )
2572             }
2573             Res::PrimTy(prim_ty) => {
2574                 assert_eq!(opt_self_ty, None);
2575                 self.prohibit_generics(path.segments.iter(), |err| {
2576                     let name = prim_ty.name_str();
2577                     for segment in path.segments {
2578                         if let Some(args) = segment.args {
2579                             err.span_suggestion_verbose(
2580                                 segment.ident.span.shrink_to_hi().to(args.span_ext),
2581                                 &format!("primitive type `{name}` doesn't have generic parameters"),
2582                                 "",
2583                                 Applicability::MaybeIncorrect,
2584                             );
2585                         }
2586                     }
2587                 });
2588                 match prim_ty {
2589                     hir::PrimTy::Bool => tcx.types.bool,
2590                     hir::PrimTy::Char => tcx.types.char,
2591                     hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2592                     hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2593                     hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2594                     hir::PrimTy::Str => tcx.types.str_,
2595                 }
2596             }
2597             Res::Err => {
2598                 self.set_tainted_by_errors();
2599                 self.tcx().ty_error()
2600             }
2601             _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2602         }
2603     }
2604
2605     /// Parses the programmer's textual representation of a type into our
2606     /// internal notion of a type.
2607     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2608         self.ast_ty_to_ty_inner(ast_ty, false, false)
2609     }
2610
2611     /// Parses the programmer's textual representation of a type into our
2612     /// internal notion of a type.  This is meant to be used within a path.
2613     pub fn ast_ty_to_ty_in_path(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2614         self.ast_ty_to_ty_inner(ast_ty, false, true)
2615     }
2616
2617     /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2618     /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2619     #[instrument(level = "debug", skip(self), ret)]
2620     fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool, in_path: bool) -> Ty<'tcx> {
2621         let tcx = self.tcx();
2622
2623         let result_ty = match ast_ty.kind {
2624             hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(ty)),
2625             hir::TyKind::Ptr(ref mt) => {
2626                 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl })
2627             }
2628             hir::TyKind::Rptr(ref region, ref mt) => {
2629                 let r = self.ast_region_to_region(region, None);
2630                 debug!(?r);
2631                 let t = self.ast_ty_to_ty_inner(mt.ty, true, false);
2632                 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2633             }
2634             hir::TyKind::Never => tcx.types.never,
2635             hir::TyKind::Tup(fields) => tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(t))),
2636             hir::TyKind::BareFn(bf) => {
2637                 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span);
2638
2639                 tcx.mk_fn_ptr(self.ty_of_fn(
2640                     ast_ty.hir_id,
2641                     bf.unsafety,
2642                     bf.abi,
2643                     bf.decl,
2644                     None,
2645                     Some(ast_ty),
2646                 ))
2647             }
2648             hir::TyKind::TraitObject(bounds, ref lifetime, repr) => {
2649                 self.maybe_lint_bare_trait(ast_ty, in_path);
2650                 let repr = match repr {
2651                     TraitObjectSyntax::Dyn | TraitObjectSyntax::None => ty::Dyn,
2652                     TraitObjectSyntax::DynStar => ty::DynStar,
2653                 };
2654                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed, repr)
2655             }
2656             hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2657                 debug!(?maybe_qself, ?path);
2658                 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2659                 self.res_to_ty(opt_self_ty, path, false)
2660             }
2661             hir::TyKind::OpaqueDef(item_id, lifetimes, in_trait) => {
2662                 let opaque_ty = tcx.hir().item(item_id);
2663                 let def_id = item_id.owner_id.to_def_id();
2664
2665                 match opaque_ty.kind {
2666                     hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
2667                         self.impl_trait_ty_to_ty(def_id, lifetimes, origin, in_trait)
2668                     }
2669                     ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2670                 }
2671             }
2672             hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2673                 debug!(?qself, ?segment);
2674                 let ty = self.ast_ty_to_ty_inner(qself, false, true);
2675                 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, qself, segment, false)
2676                     .map(|(ty, _, _)| ty)
2677                     .unwrap_or_else(|_| tcx.ty_error())
2678             }
2679             hir::TyKind::Path(hir::QPath::LangItem(lang_item, span, _)) => {
2680                 let def_id = tcx.require_lang_item(lang_item, Some(span));
2681                 let (substs, _) = self.create_substs_for_ast_path(
2682                     span,
2683                     def_id,
2684                     &[],
2685                     &hir::PathSegment::invalid(),
2686                     &GenericArgs::none(),
2687                     true,
2688                     None,
2689                     None,
2690                 );
2691                 EarlyBinder(self.normalize_ty(span, tcx.at(span).type_of(def_id)))
2692                     .subst(tcx, substs)
2693             }
2694             hir::TyKind::Array(ref ty, ref length) => {
2695                 let length = match length {
2696                     &hir::ArrayLen::Infer(_, span) => self.ct_infer(tcx.types.usize, None, span),
2697                     hir::ArrayLen::Body(constant) => {
2698                         let length_def_id = tcx.hir().local_def_id(constant.hir_id);
2699                         ty::Const::from_anon_const(tcx, length_def_id)
2700                     }
2701                 };
2702
2703                 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(ty), length));
2704                 self.normalize_ty(ast_ty.span, array_ty)
2705             }
2706             hir::TyKind::Typeof(ref e) => {
2707                 let ty_erased = tcx.type_of(tcx.hir().local_def_id(e.hir_id));
2708                 let ty = tcx.fold_regions(ty_erased, |r, _| {
2709                     if r.is_erased() { tcx.lifetimes.re_static } else { r }
2710                 });
2711                 let span = ast_ty.span;
2712                 tcx.sess.emit_err(TypeofReservedKeywordUsed {
2713                     span,
2714                     ty,
2715                     opt_sugg: Some((span, Applicability::MachineApplicable))
2716                         .filter(|_| ty.is_suggestable(tcx, false)),
2717                 });
2718
2719                 ty
2720             }
2721             hir::TyKind::Infer => {
2722                 // Infer also appears as the type of arguments or return
2723                 // values in an ExprKind::Closure, or as
2724                 // the type of local variables. Both of these cases are
2725                 // handled specially and will not descend into this routine.
2726                 self.ty_infer(None, ast_ty.span)
2727             }
2728             hir::TyKind::Err => tcx.ty_error(),
2729         };
2730
2731         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2732         result_ty
2733     }
2734
2735     #[instrument(level = "debug", skip(self), ret)]
2736     fn impl_trait_ty_to_ty(
2737         &self,
2738         def_id: DefId,
2739         lifetimes: &[hir::GenericArg<'_>],
2740         origin: OpaqueTyOrigin,
2741         in_trait: bool,
2742     ) -> Ty<'tcx> {
2743         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2744         let tcx = self.tcx();
2745
2746         let generics = tcx.generics_of(def_id);
2747
2748         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2749         let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2750             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2751                 // Our own parameters are the resolved lifetimes.
2752                 if let GenericParamDefKind::Lifetime = param.kind {
2753                     if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2754                         self.ast_region_to_region(lifetime, None).into()
2755                     } else {
2756                         bug!()
2757                     }
2758                 } else {
2759                     bug!()
2760                 }
2761             } else {
2762                 match param.kind {
2763                     // For RPIT (return position impl trait), only lifetimes
2764                     // mentioned in the impl Trait predicate are captured by
2765                     // the opaque type, so the lifetime parameters from the
2766                     // parent item need to be replaced with `'static`.
2767                     //
2768                     // For `impl Trait` in the types of statics, constants,
2769                     // locals and type aliases. These capture all parent
2770                     // lifetimes, so they can use their identity subst.
2771                     GenericParamDefKind::Lifetime
2772                         if matches!(
2773                             origin,
2774                             hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..)
2775                         ) =>
2776                     {
2777                         tcx.lifetimes.re_static.into()
2778                     }
2779                     _ => tcx.mk_param_from_def(param),
2780                 }
2781             }
2782         });
2783         debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2784
2785         if in_trait { tcx.mk_projection(def_id, substs) } else { tcx.mk_opaque(def_id, substs) }
2786     }
2787
2788     pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2789         match ty.kind {
2790             hir::TyKind::Infer if expected_ty.is_some() => {
2791                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2792                 expected_ty.unwrap()
2793             }
2794             _ => self.ast_ty_to_ty(ty),
2795         }
2796     }
2797
2798     #[instrument(level = "debug", skip(self, hir_id, unsafety, abi, decl, generics, hir_ty), ret)]
2799     pub fn ty_of_fn(
2800         &self,
2801         hir_id: hir::HirId,
2802         unsafety: hir::Unsafety,
2803         abi: abi::Abi,
2804         decl: &hir::FnDecl<'_>,
2805         generics: Option<&hir::Generics<'_>>,
2806         hir_ty: Option<&hir::Ty<'_>>,
2807     ) -> ty::PolyFnSig<'tcx> {
2808         let tcx = self.tcx();
2809         let bound_vars = tcx.late_bound_vars(hir_id);
2810         debug!(?bound_vars);
2811
2812         // We proactively collect all the inferred type params to emit a single error per fn def.
2813         let mut visitor = HirPlaceholderCollector::default();
2814         let mut infer_replacements = vec![];
2815
2816         if let Some(generics) = generics {
2817             walk_generics(&mut visitor, generics);
2818         }
2819
2820         let input_tys: Vec<_> = decl
2821             .inputs
2822             .iter()
2823             .enumerate()
2824             .map(|(i, a)| {
2825                 if let hir::TyKind::Infer = a.kind && !self.allow_ty_infer() {
2826                     if let Some(suggested_ty) =
2827                         self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i))
2828                     {
2829                         infer_replacements.push((a.span, suggested_ty.to_string()));
2830                         return suggested_ty;
2831                     }
2832                 }
2833
2834                 // Only visit the type looking for `_` if we didn't fix the type above
2835                 visitor.visit_ty(a);
2836                 self.ty_of_arg(a, None)
2837             })
2838             .collect();
2839
2840         let output_ty = match decl.output {
2841             hir::FnRetTy::Return(output) => {
2842                 if let hir::TyKind::Infer = output.kind
2843                     && !self.allow_ty_infer()
2844                     && let Some(suggested_ty) =
2845                         self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, None)
2846                 {
2847                     infer_replacements.push((output.span, suggested_ty.to_string()));
2848                     suggested_ty
2849                 } else {
2850                     visitor.visit_ty(output);
2851                     self.ast_ty_to_ty(output)
2852                 }
2853             }
2854             hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2855         };
2856
2857         debug!(?output_ty);
2858
2859         let fn_ty = tcx.mk_fn_sig(input_tys.into_iter(), output_ty, decl.c_variadic, unsafety, abi);
2860         let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
2861
2862         if !self.allow_ty_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) {
2863             // We always collect the spans for placeholder types when evaluating `fn`s, but we
2864             // only want to emit an error complaining about them if infer types (`_`) are not
2865             // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2866             // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2867
2868             let mut diag = crate::collect::placeholder_type_error_diag(
2869                 tcx,
2870                 generics,
2871                 visitor.0,
2872                 infer_replacements.iter().map(|(s, _)| *s).collect(),
2873                 true,
2874                 hir_ty,
2875                 "function",
2876             );
2877
2878             if !infer_replacements.is_empty() {
2879                 diag.multipart_suggestion(
2880                     &format!(
2881                     "try replacing `_` with the type{} in the corresponding trait method signature",
2882                     rustc_errors::pluralize!(infer_replacements.len()),
2883                 ),
2884                     infer_replacements,
2885                     Applicability::MachineApplicable,
2886                 );
2887             }
2888
2889             diag.emit();
2890         }
2891
2892         // Find any late-bound regions declared in return type that do
2893         // not appear in the arguments. These are not well-formed.
2894         //
2895         // Example:
2896         //     for<'a> fn() -> &'a str <-- 'a is bad
2897         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2898         let inputs = bare_fn_ty.inputs();
2899         let late_bound_in_args =
2900             tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2901         let output = bare_fn_ty.output();
2902         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2903
2904         self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2905             struct_span_err!(
2906                 tcx.sess,
2907                 decl.output.span(),
2908                 E0581,
2909                 "return type references {}, which is not constrained by the fn input types",
2910                 br_name
2911             )
2912         });
2913
2914         bare_fn_ty
2915     }
2916
2917     /// Given a fn_hir_id for a impl function, suggest the type that is found on the
2918     /// corresponding function in the trait that the impl implements, if it exists.
2919     /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
2920     /// corresponds to the return type.
2921     fn suggest_trait_fn_ty_for_impl_fn_infer(
2922         &self,
2923         fn_hir_id: hir::HirId,
2924         arg_idx: Option<usize>,
2925     ) -> Option<Ty<'tcx>> {
2926         let tcx = self.tcx();
2927         let hir = tcx.hir();
2928
2929         let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
2930             hir.get(fn_hir_id) else { return None };
2931         let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(i), .. }) =
2932                 hir.get(hir.get_parent_node(fn_hir_id)) else { bug!("ImplItem should have Impl parent") };
2933
2934         let trait_ref = self.instantiate_mono_trait_ref(
2935             i.of_trait.as_ref()?,
2936             self.ast_ty_to_ty(i.self_ty),
2937             ty::BoundConstness::NotConst,
2938         );
2939
2940         let assoc = tcx.associated_items(trait_ref.def_id).find_by_name_and_kind(
2941             tcx,
2942             *ident,
2943             ty::AssocKind::Fn,
2944             trait_ref.def_id,
2945         )?;
2946
2947         let fn_sig = tcx.bound_fn_sig(assoc.def_id).subst(
2948             tcx,
2949             trait_ref.substs.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
2950         );
2951
2952         let ty = if let Some(arg_idx) = arg_idx { fn_sig.input(arg_idx) } else { fn_sig.output() };
2953
2954         Some(tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), ty))
2955     }
2956
2957     fn validate_late_bound_regions(
2958         &self,
2959         constrained_regions: FxHashSet<ty::BoundRegionKind>,
2960         referenced_regions: FxHashSet<ty::BoundRegionKind>,
2961         generate_err: impl Fn(&str) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
2962     ) {
2963         for br in referenced_regions.difference(&constrained_regions) {
2964             let br_name = match *br {
2965                 ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(_) | ty::BrEnv => {
2966                     "an anonymous lifetime".to_string()
2967                 }
2968                 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
2969             };
2970
2971             let mut err = generate_err(&br_name);
2972
2973             if let ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(_) = *br {
2974                 // The only way for an anonymous lifetime to wind up
2975                 // in the return type but **also** be unconstrained is
2976                 // if it only appears in "associated types" in the
2977                 // input. See #47511 and #62200 for examples. In this case,
2978                 // though we can easily give a hint that ought to be
2979                 // relevant.
2980                 err.note(
2981                     "lifetimes appearing in an associated or opaque type are not considered constrained",
2982                 );
2983                 err.note("consider introducing a named lifetime parameter");
2984             }
2985
2986             err.emit();
2987         }
2988     }
2989
2990     /// Given the bounds on an object, determines what single region bound (if any) we can
2991     /// use to summarize this type. The basic idea is that we will use the bound the user
2992     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2993     /// for region bounds. It may be that we can derive no bound at all, in which case
2994     /// we return `None`.
2995     fn compute_object_lifetime_bound(
2996         &self,
2997         span: Span,
2998         existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2999     ) -> Option<ty::Region<'tcx>> // if None, use the default
3000     {
3001         let tcx = self.tcx();
3002
3003         debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
3004
3005         // No explicit region bound specified. Therefore, examine trait
3006         // bounds and see if we can derive region bounds from those.
3007         let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3008
3009         // If there are no derived region bounds, then report back that we
3010         // can find no region bound. The caller will use the default.
3011         if derived_region_bounds.is_empty() {
3012             return None;
3013         }
3014
3015         // If any of the derived region bounds are 'static, that is always
3016         // the best choice.
3017         if derived_region_bounds.iter().any(|r| r.is_static()) {
3018             return Some(tcx.lifetimes.re_static);
3019         }
3020
3021         // Determine whether there is exactly one unique region in the set
3022         // of derived region bounds. If so, use that. Otherwise, report an
3023         // error.
3024         let r = derived_region_bounds[0];
3025         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3026             tcx.sess.emit_err(AmbiguousLifetimeBound { span });
3027         }
3028         Some(r)
3029     }
3030
3031     /// Make sure that we are in the condition to suggest the blanket implementation.
3032     fn maybe_lint_blanket_trait_impl(&self, self_ty: &hir::Ty<'_>, diag: &mut Diagnostic) {
3033         let tcx = self.tcx();
3034         let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
3035         if let hir::Node::Item(hir::Item {
3036             kind:
3037                 hir::ItemKind::Impl(hir::Impl {
3038                     self_ty: impl_self_ty, of_trait: Some(of_trait_ref), generics, ..
3039                 }),
3040             ..
3041         }) = tcx.hir().get_by_def_id(parent_id) && self_ty.hir_id == impl_self_ty.hir_id
3042         {
3043             if !of_trait_ref.trait_def_id().map_or(false, |def_id| def_id.is_local()) {
3044                 return;
3045             }
3046             let of_trait_span = of_trait_ref.path.span;
3047             // make sure that we are not calling unwrap to abort during the compilation
3048             let Ok(impl_trait_name) = tcx.sess.source_map().span_to_snippet(self_ty.span) else { return; };
3049             let Ok(of_trait_name) = tcx.sess.source_map().span_to_snippet(of_trait_span) else { return; };
3050             // check if the trait has generics, to make a correct suggestion
3051             let param_name = generics.params.next_type_param_name(None);
3052
3053             let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() {
3054                 (span, format!(", {}: {}", param_name, impl_trait_name))
3055             } else {
3056                 (generics.span, format!("<{}: {}>", param_name, impl_trait_name))
3057             };
3058             diag.multipart_suggestion(
3059             format!("alternatively use a blanket \
3060                      implementation to implement `{of_trait_name}` for \
3061                      all types that also implement `{impl_trait_name}`"),
3062                 vec![
3063                     (self_ty.span, param_name),
3064                     add_generic_sugg,
3065                 ],
3066                 Applicability::MaybeIncorrect,
3067             );
3068         }
3069     }
3070
3071     fn maybe_lint_bare_trait(&self, self_ty: &hir::Ty<'_>, in_path: bool) {
3072         let tcx = self.tcx();
3073         if let hir::TyKind::TraitObject([poly_trait_ref, ..], _, TraitObjectSyntax::None) =
3074             self_ty.kind
3075         {
3076             let needs_bracket = in_path
3077                 && !tcx
3078                     .sess
3079                     .source_map()
3080                     .span_to_prev_source(self_ty.span)
3081                     .ok()
3082                     .map_or(false, |s| s.trim_end().ends_with('<'));
3083
3084             let is_global = poly_trait_ref.trait_ref.path.is_global();
3085
3086             let mut sugg = Vec::from_iter([(
3087                 self_ty.span.shrink_to_lo(),
3088                 format!(
3089                     "{}dyn {}",
3090                     if needs_bracket { "<" } else { "" },
3091                     if is_global { "(" } else { "" },
3092                 ),
3093             )]);
3094
3095             if is_global || needs_bracket {
3096                 sugg.push((
3097                     self_ty.span.shrink_to_hi(),
3098                     format!(
3099                         "{}{}",
3100                         if is_global { ")" } else { "" },
3101                         if needs_bracket { ">" } else { "" },
3102                     ),
3103                 ));
3104             }
3105
3106             if self_ty.span.edition() >= Edition::Edition2021 {
3107                 let msg = "trait objects must include the `dyn` keyword";
3108                 let label = "add `dyn` keyword before this trait";
3109                 let mut diag =
3110                     rustc_errors::struct_span_err!(tcx.sess, self_ty.span, E0782, "{}", msg);
3111                 diag.multipart_suggestion_verbose(label, sugg, Applicability::MachineApplicable);
3112                 // check if the impl trait that we are considering is a impl of a local trait
3113                 self.maybe_lint_blanket_trait_impl(&self_ty, &mut diag);
3114                 diag.emit();
3115             } else {
3116                 let msg = "trait objects without an explicit `dyn` are deprecated";
3117                 tcx.struct_span_lint_hir(
3118                     BARE_TRAIT_OBJECTS,
3119                     self_ty.hir_id,
3120                     self_ty.span,
3121                     msg,
3122                     |lint| {
3123                         lint.multipart_suggestion_verbose(
3124                             "use `dyn`",
3125                             sugg,
3126                             Applicability::MachineApplicable,
3127                         );
3128                         self.maybe_lint_blanket_trait_impl(&self_ty, lint);
3129                         lint
3130                     },
3131                 );
3132             }
3133         }
3134     }
3135 }