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