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