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