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