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