]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/astconv/mod.rs
fix: misleading add `dyn` to derive macro suggestion
[rust.git] / compiler / rustc_hir_analysis / src / astconv / mod.rs
1 //! Conversion from AST representation of types to the `ty.rs` representation.
2 //! The main routine here is `ast_ty_to_ty()`; each use is parameterized by an
3 //! instance of `AstConv`.
4
5 mod errors;
6 pub mod generics;
7
8 use crate::astconv::generics::{
9     check_generic_arg_count, create_substs_for_generic_args, prohibit_assoc_ty_binding,
10 };
11 use crate::bounds::Bounds;
12 use crate::collect::HirPlaceholderCollector;
13 use crate::errors::{
14     AmbiguousLifetimeBound, MultipleRelaxedDefaultBounds, TraitObjectDeclaredWithNoTraits,
15     TypeofReservedKeywordUsed, ValueOfAssociatedStructAlreadySpecified,
16 };
17 use crate::middle::resolve_lifetime as rl;
18 use crate::require_c_abi_if_c_variadic;
19 use rustc_ast::TraitObjectSyntax;
20 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
21 use rustc_errors::{
22     struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, FatalError,
23     MultiSpan,
24 };
25 use rustc_hir as hir;
26 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
27 use rustc_hir::def_id::{DefId, LocalDefId};
28 use rustc_hir::intravisit::{walk_generics, Visitor as _};
29 use rustc_hir::{GenericArg, GenericArgs, OpaqueTyOrigin};
30 use rustc_infer::infer::TyCtxtInferExt;
31 use rustc_middle::middle::stability::AllowUnstable;
32 use rustc_middle::ty::subst::{self, GenericArgKind, InternalSubsts, SubstsRef};
33 use rustc_middle::ty::GenericParamDefKind;
34 use rustc_middle::ty::{self, Const, DefIdTree, IsSuggestable, Ty, TyCtxt, TypeVisitable};
35 use rustc_middle::ty::{DynKind, EarlyBinder};
36 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, BARE_TRAIT_OBJECTS};
37 use rustc_span::edition::Edition;
38 use rustc_span::lev_distance::find_best_match_for_name;
39 use rustc_span::symbol::{kw, Ident, Symbol};
40 use rustc_span::{sym, Span};
41 use rustc_target::spec::abi;
42 use rustc_trait_selection::traits;
43 use rustc_trait_selection::traits::astconv_object_safety_violations;
44 use rustc_trait_selection::traits::error_reporting::{
45     report_object_safety_error, suggestions::NextTypeParamName,
46 };
47 use rustc_trait_selection::traits::wf::object_region_bounds;
48
49 use smallvec::{smallvec, SmallVec};
50 use std::collections::BTreeSet;
51 use std::slice;
52
53 #[derive(Debug)]
54 pub struct PathSeg(pub DefId, pub usize);
55
56 pub trait AstConv<'tcx> {
57     fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
58
59     fn item_def_id(&self) -> DefId;
60
61     /// Returns predicates in scope of the form `X: Foo<T>`, where `X`
62     /// is a type parameter `X` with the given id `def_id` and T
63     /// matches `assoc_name`. This is a subset of the full set of
64     /// predicates.
65     ///
66     /// This is used for one specific purpose: resolving "short-hand"
67     /// associated type references like `T::Item`. In principle, we
68     /// would do that by first getting the full set of predicates in
69     /// scope and then filtering down to find those that apply to `T`,
70     /// but this can lead to cycle errors. The problem is that we have
71     /// to do this resolution *in order to create the predicates in
72     /// the first place*. Hence, we have this "special pass".
73     fn get_type_parameter_bounds(
74         &self,
75         span: Span,
76         def_id: DefId,
77         assoc_name: Ident,
78     ) -> ty::GenericPredicates<'tcx>;
79
80     /// Returns the lifetime to use when a lifetime is omitted (and not elided).
81     fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
82     -> Option<ty::Region<'tcx>>;
83
84     /// Returns the type to use when a type is omitted.
85     fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
86
87     /// Returns `true` if `_` is allowed in type signatures in the current context.
88     fn allow_ty_infer(&self) -> bool;
89
90     /// Returns the const to use when a const is omitted.
91     fn ct_infer(
92         &self,
93         ty: Ty<'tcx>,
94         param: Option<&ty::GenericParamDef>,
95         span: Span,
96     ) -> Const<'tcx>;
97
98     /// Projecting an associated type from a (potentially)
99     /// higher-ranked trait reference is more complicated, because of
100     /// the possibility of late-bound regions appearing in the
101     /// associated type binding. This is not legal in function
102     /// signatures for that reason. In a function body, we can always
103     /// handle it because we can use inference variables to remove the
104     /// late-bound regions.
105     fn projected_ty_from_poly_trait_ref(
106         &self,
107         span: Span,
108         item_def_id: DefId,
109         item_segment: &hir::PathSegment<'_>,
110         poly_trait_ref: ty::PolyTraitRef<'tcx>,
111     ) -> Ty<'tcx>;
112
113     /// Returns `AdtDef` if `ty` is an ADT.
114     /// Note that `ty` might be a projection type that needs normalization.
115     /// This used to get the enum variants in scope of the type.
116     /// For example, `Self::A` could refer to an associated type
117     /// or to an enum variant depending on the result of this function.
118     fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
119
120     /// Invoked when we encounter an error from some prior pass
121     /// (e.g., resolve) that is translated into a ty-error. This is
122     /// used to help suppress derived errors typeck might otherwise
123     /// report.
124     fn set_tainted_by_errors(&self, e: ErrorGuaranteed);
125
126     fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
127
128     fn astconv(&self) -> &dyn AstConv<'tcx>
129     where
130         Self: Sized,
131     {
132         self
133     }
134 }
135
136 #[derive(Debug)]
137 struct ConvertedBinding<'a, 'tcx> {
138     hir_id: hir::HirId,
139     item_name: Ident,
140     kind: ConvertedBindingKind<'a, 'tcx>,
141     gen_args: &'a GenericArgs<'a>,
142     span: Span,
143 }
144
145 #[derive(Debug)]
146 enum ConvertedBindingKind<'a, 'tcx> {
147     Equality(ty::Term<'tcx>),
148     Constraint(&'a [hir::GenericBound<'a>]),
149 }
150
151 /// New-typed boolean indicating whether explicit late-bound lifetimes
152 /// are present in a set of generic arguments.
153 ///
154 /// For example if we have some method `fn f<'a>(&'a self)` implemented
155 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
156 /// is late-bound so should not be provided explicitly. Thus, if `f` is
157 /// instantiated with some generic arguments providing `'a` explicitly,
158 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
159 /// can provide an appropriate diagnostic later.
160 #[derive(Copy, Clone, PartialEq, Debug)]
161 pub enum ExplicitLateBound {
162     Yes,
163     No,
164 }
165
166 #[derive(Copy, Clone, PartialEq)]
167 pub enum IsMethodCall {
168     Yes,
169     No,
170 }
171
172 /// Denotes the "position" of a generic argument, indicating if it is a generic type,
173 /// generic function or generic method call.
174 #[derive(Copy, Clone, PartialEq)]
175 pub(crate) enum GenericArgPosition {
176     Type,
177     Value, // e.g., functions
178     MethodCall,
179 }
180
181 /// A marker denoting that the generic arguments that were
182 /// provided did not match the respective generic parameters.
183 #[derive(Clone, Default, Debug)]
184 pub struct GenericArgCountMismatch {
185     /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
186     pub reported: Option<ErrorGuaranteed>,
187     /// A list of spans of arguments provided that were not valid.
188     pub invalid_args: Vec<Span>,
189 }
190
191 /// Decorates the result of a generic argument count mismatch
192 /// check with whether explicit late bounds were provided.
193 #[derive(Clone, Debug)]
194 pub struct GenericArgCountResult {
195     pub explicit_late_bound: ExplicitLateBound,
196     pub correct: Result<(), GenericArgCountMismatch>,
197 }
198
199 pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> {
200     fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
201
202     fn provided_kind(
203         &mut self,
204         param: &ty::GenericParamDef,
205         arg: &GenericArg<'_>,
206     ) -> subst::GenericArg<'tcx>;
207
208     fn inferred_kind(
209         &mut self,
210         substs: Option<&[subst::GenericArg<'tcx>]>,
211         param: &ty::GenericParamDef,
212         infer_args: bool,
213     ) -> subst::GenericArg<'tcx>;
214 }
215
216 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
217     #[instrument(level = "debug", skip(self), ret)]
218     pub fn ast_region_to_region(
219         &self,
220         lifetime: &hir::Lifetime,
221         def: Option<&ty::GenericParamDef>,
222     ) -> ty::Region<'tcx> {
223         let tcx = self.tcx();
224         let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
225
226         match tcx.named_region(lifetime.hir_id) {
227             Some(rl::Region::Static) => tcx.lifetimes.re_static,
228
229             Some(rl::Region::LateBound(debruijn, index, def_id)) => {
230                 let name = lifetime_name(def_id.expect_local());
231                 let br = ty::BoundRegion {
232                     var: ty::BoundVar::from_u32(index),
233                     kind: ty::BrNamed(def_id, name),
234                 };
235                 tcx.mk_region(ty::ReLateBound(debruijn, br))
236             }
237
238             Some(rl::Region::EarlyBound(def_id)) => {
239                 let name = tcx.hir().ty_param_name(def_id.expect_local());
240                 let item_def_id = tcx.hir().ty_param_owner(def_id.expect_local());
241                 let generics = tcx.generics_of(item_def_id);
242                 let index = generics.param_def_id_to_index[&def_id];
243                 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, index, name }))
244             }
245
246             Some(rl::Region::Free(scope, id)) => {
247                 let name = lifetime_name(id.expect_local());
248                 tcx.mk_region(ty::ReFree(ty::FreeRegion {
249                     scope,
250                     bound_region: ty::BrNamed(id, name),
251                 }))
252
253                 // (*) -- not late-bound, won't change
254             }
255
256             None => {
257                 self.re_infer(def, lifetime.ident.span).unwrap_or_else(|| {
258                     debug!(?lifetime, "unelided lifetime in signature");
259
260                     // This indicates an illegal lifetime
261                     // elision. `resolve_lifetime` should have
262                     // reported an error in this case -- but if
263                     // not, let's error out.
264                     tcx.sess.delay_span_bug(lifetime.ident.span, "unelided lifetime in signature");
265
266                     // Supply some dummy value. We don't have an
267                     // `re_error`, annoyingly, so use `'static`.
268                     tcx.lifetimes.re_static
269                 })
270             }
271         }
272     }
273
274     /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
275     /// returns an appropriate set of substitutions for this particular reference to `I`.
276     pub fn ast_path_substs_for_ty(
277         &self,
278         span: Span,
279         def_id: DefId,
280         item_segment: &hir::PathSegment<'_>,
281     ) -> SubstsRef<'tcx> {
282         let (substs, _) = self.create_substs_for_ast_path(
283             span,
284             def_id,
285             &[],
286             item_segment,
287             item_segment.args(),
288             item_segment.infer_args,
289             None,
290             ty::BoundConstness::NotConst,
291         );
292         if let Some(b) = item_segment.args().bindings.first() {
293             prohibit_assoc_ty_binding(self.tcx(), b.span);
294         }
295
296         substs
297     }
298
299     /// Given the type/lifetime/const arguments provided to some path (along with
300     /// an implicit `Self`, if this is a trait reference), returns the complete
301     /// set of substitutions. This may involve applying defaulted type parameters.
302     /// Constraints on associated types are created from `create_assoc_bindings_for_generic_args`.
303     ///
304     /// Example:
305     ///
306     /// ```ignore (illustrative)
307     ///    T: std::ops::Index<usize, Output = u32>
308     /// // ^1 ^^^^^^^^^^^^^^2 ^^^^3  ^^^^^^^^^^^4
309     /// ```
310     ///
311     /// 1. The `self_ty` here would refer to the type `T`.
312     /// 2. The path in question is the path to the trait `std::ops::Index`,
313     ///    which will have been resolved to a `def_id`
314     /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
315     ///    parameters are returned in the `SubstsRef`, the associated type bindings like
316     ///    `Output = u32` are returned from `create_assoc_bindings_for_generic_args`.
317     ///
318     /// Note that the type listing given here is *exactly* what the user provided.
319     ///
320     /// For (generic) associated types
321     ///
322     /// ```ignore (illustrative)
323     /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
324     /// ```
325     ///
326     /// We have the parent substs are the substs for the parent trait:
327     /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
328     /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
329     /// lists: `[Vec<u8>, u8, 'a]`.
330     #[instrument(level = "debug", skip(self, span), ret)]
331     fn create_substs_for_ast_path<'a>(
332         &self,
333         span: Span,
334         def_id: DefId,
335         parent_substs: &[subst::GenericArg<'tcx>],
336         seg: &hir::PathSegment<'_>,
337         generic_args: &'a hir::GenericArgs<'_>,
338         infer_args: bool,
339         self_ty: Option<Ty<'tcx>>,
340         constness: ty::BoundConstness,
341     ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
342         // If the type is parameterized by this region, then replace this
343         // region with the current anon region binding (in other words,
344         // whatever & would get replaced with).
345
346         let tcx = self.tcx();
347         let generics = tcx.generics_of(def_id);
348         debug!("generics: {:?}", generics);
349
350         if generics.has_self {
351             if generics.parent.is_some() {
352                 // The parent is a trait so it should have at least one subst
353                 // for the `Self` type.
354                 assert!(!parent_substs.is_empty())
355             } else {
356                 // This item (presumably a trait) needs a self-type.
357                 assert!(self_ty.is_some());
358             }
359         } else {
360             assert!(self_ty.is_none());
361         }
362
363         let arg_count = check_generic_arg_count(
364             tcx,
365             span,
366             def_id,
367             seg,
368             generics,
369             generic_args,
370             GenericArgPosition::Type,
371             self_ty.is_some(),
372             infer_args,
373         );
374
375         // Skip processing if type has no generic parameters.
376         // Traits always have `Self` as a generic parameter, which means they will not return early
377         // here and so associated type bindings will be handled regardless of whether there are any
378         // non-`Self` generic parameters.
379         if generics.params.is_empty() {
380             return (tcx.intern_substs(parent_substs), arg_count);
381         }
382
383         struct SubstsForAstPathCtxt<'a, 'tcx> {
384             astconv: &'a (dyn AstConv<'tcx> + 'a),
385             def_id: DefId,
386             generic_args: &'a GenericArgs<'a>,
387             span: Span,
388             inferred_params: Vec<Span>,
389             infer_args: bool,
390         }
391
392         impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> {
393             fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) {
394                 if did == self.def_id {
395                     (Some(self.generic_args), self.infer_args)
396                 } else {
397                     // The last component of this tuple is unimportant.
398                     (None, false)
399                 }
400             }
401
402             fn provided_kind(
403                 &mut self,
404                 param: &ty::GenericParamDef,
405                 arg: &GenericArg<'_>,
406             ) -> subst::GenericArg<'tcx> {
407                 let tcx = self.astconv.tcx();
408
409                 let mut handle_ty_args = |has_default, ty: &hir::Ty<'_>| {
410                     if has_default {
411                         tcx.check_optional_stability(
412                             param.def_id,
413                             Some(arg.hir_id()),
414                             arg.span(),
415                             None,
416                             AllowUnstable::No,
417                             |_, _| {
418                                 // Default generic parameters may not be marked
419                                 // with stability attributes, i.e. when the
420                                 // default parameter was defined at the same time
421                                 // as the rest of the type. As such, we ignore missing
422                                 // stability attributes.
423                             },
424                         );
425                     }
426                     if let (hir::TyKind::Infer, false) = (&ty.kind, self.astconv.allow_ty_infer()) {
427                         self.inferred_params.push(ty.span);
428                         tcx.ty_error().into()
429                     } else {
430                         self.astconv.ast_ty_to_ty(ty).into()
431                     }
432                 };
433
434                 match (&param.kind, arg) {
435                     (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
436                         self.astconv.ast_region_to_region(lt, Some(param)).into()
437                     }
438                     (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
439                         handle_ty_args(has_default, ty)
440                     }
441                     (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
442                         handle_ty_args(has_default, &inf.to_ty())
443                     }
444                     (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
445                         ty::Const::from_opt_const_arg_anon_const(
446                             tcx,
447                             ty::WithOptConstParam {
448                                 did: ct.value.def_id,
449                                 const_param_did: Some(param.def_id),
450                             },
451                         )
452                         .into()
453                     }
454                     (&GenericParamDefKind::Const { .. }, hir::GenericArg::Infer(inf)) => {
455                         let ty = tcx.at(self.span).type_of(param.def_id);
456                         if self.astconv.allow_ty_infer() {
457                             self.astconv.ct_infer(ty, Some(param), inf.span).into()
458                         } else {
459                             self.inferred_params.push(inf.span);
460                             tcx.const_error(ty).into()
461                         }
462                     }
463                     _ => unreachable!(),
464                 }
465             }
466
467             fn inferred_kind(
468                 &mut self,
469                 substs: Option<&[subst::GenericArg<'tcx>]>,
470                 param: &ty::GenericParamDef,
471                 infer_args: bool,
472             ) -> subst::GenericArg<'tcx> {
473                 let tcx = self.astconv.tcx();
474                 match param.kind {
475                     GenericParamDefKind::Lifetime => self
476                         .astconv
477                         .re_infer(Some(param), self.span)
478                         .unwrap_or_else(|| {
479                             debug!(?param, "unelided lifetime in signature");
480
481                             // This indicates an illegal lifetime in a non-assoc-trait position
482                             tcx.sess.delay_span_bug(self.span, "unelided lifetime in signature");
483
484                             // Supply some dummy value. We don't have an
485                             // `re_error`, annoyingly, so use `'static`.
486                             tcx.lifetimes.re_static
487                         })
488                         .into(),
489                     GenericParamDefKind::Type { has_default, .. } => {
490                         if !infer_args && has_default {
491                             // No type parameter provided, but a default exists.
492                             let substs = substs.unwrap();
493                             if substs.iter().any(|arg| match arg.unpack() {
494                                 GenericArgKind::Type(ty) => ty.references_error(),
495                                 _ => false,
496                             }) {
497                                 // Avoid ICE #86756 when type error recovery goes awry.
498                                 return tcx.ty_error().into();
499                             }
500                             tcx.at(self.span).bound_type_of(param.def_id).subst(tcx, substs).into()
501                         } else if infer_args {
502                             self.astconv.ty_infer(Some(param), self.span).into()
503                         } else {
504                             // We've already errored above about the mismatch.
505                             tcx.ty_error().into()
506                         }
507                     }
508                     GenericParamDefKind::Const { has_default } => {
509                         let ty = tcx.at(self.span).type_of(param.def_id);
510                         if ty.references_error() {
511                             return tcx.const_error(ty).into();
512                         }
513                         if !infer_args && has_default {
514                             tcx.bound_const_param_default(param.def_id)
515                                 .subst(tcx, substs.unwrap())
516                                 .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 { ref term } => match term {
576                         hir::Term::Ty(ref ty) => {
577                             ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty).into())
578                         }
579                         hir::Term::Const(ref c) => {
580                             let c = Const::from_anon_const(self.tcx(), c.def_id);
581                             ConvertedBindingKind::Equality(c.into())
582                         }
583                     },
584                     hir::TypeBindingKind::Constraint { ref 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(_, ref 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(_, ref 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)),
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                     // Find all the `impl`s that `qself_ty` has for any trait that has the
2138                     // associated type, so that we suggest the right one.
2139                     let infcx = tcx.infer_ctxt().build();
2140                     // We create a fresh `ty::ParamEnv` instead of the one for `self.item_def_id()`
2141                     // to avoid a cycle error in `src/test/ui/resolve/issue-102946.rs`.
2142                     let param_env = ty::ParamEnv::empty();
2143                     let traits: Vec<_> = self
2144                         .tcx()
2145                         .all_traits()
2146                         .filter(|trait_def_id| {
2147                             // Consider only traits with the associated type
2148                             tcx.associated_items(*trait_def_id)
2149                                 .in_definition_order()
2150                                 .any(|i| {
2151                                     i.kind.namespace() == Namespace::TypeNS
2152                                         && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
2153                                         && matches!(i.kind, ty::AssocKind::Type)
2154                                 })
2155                             // Consider only accessible traits
2156                             && tcx.visibility(*trait_def_id)
2157                                 .is_accessible_from(self.item_def_id(), tcx)
2158                             && tcx.all_impls(*trait_def_id)
2159                                 .any(|impl_def_id| {
2160                                     let trait_ref = tcx.bound_impl_trait_ref(impl_def_id);
2161                                     trait_ref.map_or(false, |trait_ref| {
2162                                         let impl_ = trait_ref.subst(
2163                                             tcx,
2164                                             infcx.fresh_substs_for_item(span, impl_def_id),
2165                                         );
2166                                         infcx
2167                                             .can_eq(
2168                                                 param_env,
2169                                                 tcx.erase_regions(impl_.self_ty()),
2170                                                 tcx.erase_regions(qself_ty),
2171                                             )
2172                                             .is_ok()
2173                                     })
2174                                     && tcx.impl_polarity(impl_def_id) != ty::ImplPolarity::Negative
2175                                 })
2176                         })
2177                         .map(|trait_def_id| tcx.def_path_str(trait_def_id))
2178                         .collect();
2179
2180                     // Don't print `TyErr` to the user.
2181                     self.report_ambiguous_associated_type(
2182                         span,
2183                         &[qself_ty.to_string()],
2184                         &traits,
2185                         assoc_ident.name,
2186                     )
2187                 };
2188                 return Err(reported);
2189             }
2190         };
2191
2192         let trait_did = bound.def_id();
2193         let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, trait_did) else {
2194             // Assume that if it's not matched, there must be a const defined with the same name
2195             // but it was used in a type position.
2196             let msg = format!("found associated const `{assoc_ident}` when type was expected");
2197             let guar = tcx.sess.struct_span_err(span, &msg).emit();
2198             return Err(guar);
2199         };
2200
2201         let ty = self.projected_ty_from_poly_trait_ref(span, assoc_ty_did, assoc_segment, bound);
2202
2203         if let Some(variant_def_id) = variant_resolution {
2204             tcx.struct_span_lint_hir(
2205                 AMBIGUOUS_ASSOCIATED_ITEMS,
2206                 hir_ref_id,
2207                 span,
2208                 "ambiguous associated item",
2209                 |lint| {
2210                     let mut could_refer_to = |kind: DefKind, def_id, also| {
2211                         let note_msg = format!(
2212                             "`{}` could{} refer to the {} defined here",
2213                             assoc_ident,
2214                             also,
2215                             kind.descr(def_id)
2216                         );
2217                         lint.span_note(tcx.def_span(def_id), &note_msg);
2218                     };
2219
2220                     could_refer_to(DefKind::Variant, variant_def_id, "");
2221                     could_refer_to(DefKind::AssocTy, assoc_ty_did, " also");
2222
2223                     lint.span_suggestion(
2224                         span,
2225                         "use fully-qualified syntax",
2226                         format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2227                         Applicability::MachineApplicable,
2228                     );
2229
2230                     lint
2231                 },
2232             );
2233         }
2234         Ok((ty, DefKind::AssocTy, assoc_ty_did))
2235     }
2236
2237     fn lookup_assoc_ty(
2238         &self,
2239         ident: Ident,
2240         block: hir::HirId,
2241         span: Span,
2242         scope: DefId,
2243     ) -> Option<DefId> {
2244         let tcx = self.tcx();
2245         let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
2246
2247         // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
2248         // of calling `find_by_name_and_kind`.
2249         let item = tcx.associated_items(scope).in_definition_order().find(|i| {
2250             i.kind.namespace() == Namespace::TypeNS
2251                 && i.ident(tcx).normalize_to_macros_2_0() == ident
2252         })?;
2253
2254         let kind = DefKind::AssocTy;
2255         if !item.visibility(tcx).is_accessible_from(def_scope, tcx) {
2256             let kind = kind.descr(item.def_id);
2257             let msg = format!("{kind} `{ident}` is private");
2258             let def_span = self.tcx().def_span(item.def_id);
2259             tcx.sess
2260                 .struct_span_err_with_code(span, &msg, rustc_errors::error_code!(E0624))
2261                 .span_label(span, &format!("private {kind}"))
2262                 .span_label(def_span, &format!("{kind} defined here"))
2263                 .emit();
2264         }
2265         tcx.check_stability(item.def_id, Some(block), span, None);
2266
2267         Some(item.def_id)
2268     }
2269
2270     fn qpath_to_ty(
2271         &self,
2272         span: Span,
2273         opt_self_ty: Option<Ty<'tcx>>,
2274         item_def_id: DefId,
2275         trait_segment: &hir::PathSegment<'_>,
2276         item_segment: &hir::PathSegment<'_>,
2277         constness: ty::BoundConstness,
2278     ) -> Ty<'tcx> {
2279         let tcx = self.tcx();
2280
2281         let trait_def_id = tcx.parent(item_def_id);
2282
2283         debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2284
2285         let Some(self_ty) = opt_self_ty else {
2286             let path_str = tcx.def_path_str(trait_def_id);
2287
2288             let def_id = self.item_def_id();
2289
2290             debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2291
2292             let parent_def_id = def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
2293                 .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id());
2294
2295             debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2296
2297             // If the trait in segment is the same as the trait defining the item,
2298             // use the `<Self as ..>` syntax in the error.
2299             let is_part_of_self_trait_constraints = def_id == trait_def_id;
2300             let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2301
2302             let type_names = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2303                 vec!["Self".to_string()]
2304             } else {
2305                 // Find all the types that have an `impl` for the trait.
2306                 tcx.all_impls(trait_def_id)
2307                     .filter(|impl_def_id| {
2308                         // Consider only accessible traits
2309                         tcx.visibility(*impl_def_id).is_accessible_from(self.item_def_id(), tcx)
2310                             && tcx.impl_polarity(impl_def_id) != ty::ImplPolarity::Negative
2311                     })
2312                     .filter_map(|impl_def_id| tcx.impl_trait_ref(impl_def_id))
2313                     .map(|impl_| impl_.self_ty())
2314                     // We don't care about blanket impls.
2315                     .filter(|self_ty| !self_ty.has_non_region_param())
2316                     .map(|self_ty| tcx.erase_regions(self_ty).to_string())
2317                     .collect()
2318             };
2319             // FIXME: also look at `tcx.generics_of(self.item_def_id()).params` any that
2320             // references the trait. Relevant for the first case in
2321             // `src/test/ui/associated-types/associated-types-in-ambiguous-context.rs`
2322             let reported = self.report_ambiguous_associated_type(
2323                 span,
2324                 &type_names,
2325                 &[path_str],
2326                 item_segment.ident.name,
2327             );
2328             return tcx.ty_error_with_guaranteed(reported)
2329         };
2330
2331         debug!("qpath_to_ty: self_type={:?}", self_ty);
2332
2333         let trait_ref = self.ast_path_to_mono_trait_ref(
2334             span,
2335             trait_def_id,
2336             self_ty,
2337             trait_segment,
2338             false,
2339             constness,
2340         );
2341
2342         let item_substs = self.create_substs_for_associated_item(
2343             span,
2344             item_def_id,
2345             item_segment,
2346             trait_ref.substs,
2347         );
2348
2349         debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2350
2351         tcx.mk_projection(item_def_id, item_substs)
2352     }
2353
2354     pub fn prohibit_generics<'a>(
2355         &self,
2356         segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
2357         extend: impl Fn(&mut Diagnostic),
2358     ) -> bool {
2359         let args = segments.clone().flat_map(|segment| segment.args().args);
2360
2361         let (lt, ty, ct, inf) =
2362             args.clone().fold((false, false, false, false), |(lt, ty, ct, inf), arg| match arg {
2363                 hir::GenericArg::Lifetime(_) => (true, ty, ct, inf),
2364                 hir::GenericArg::Type(_) => (lt, true, ct, inf),
2365                 hir::GenericArg::Const(_) => (lt, ty, true, inf),
2366                 hir::GenericArg::Infer(_) => (lt, ty, ct, true),
2367             });
2368         let mut emitted = false;
2369         if lt || ty || ct || inf {
2370             let types_and_spans: Vec<_> = segments
2371                 .clone()
2372                 .flat_map(|segment| {
2373                     if segment.args().args.is_empty() {
2374                         None
2375                     } else {
2376                         Some((
2377                             match segment.res {
2378                                 Res::PrimTy(ty) => format!("{} `{}`", segment.res.descr(), ty.name()),
2379                                 Res::Def(_, def_id)
2380                                 if let Some(name) = self.tcx().opt_item_name(def_id) => {
2381                                     format!("{} `{name}`", segment.res.descr())
2382                                 }
2383                                 Res::Err => "this type".to_string(),
2384                                 _ => segment.res.descr().to_string(),
2385                             },
2386                             segment.ident.span,
2387                         ))
2388                     }
2389                 })
2390                 .collect();
2391             let this_type = match &types_and_spans[..] {
2392                 [.., _, (last, _)] => format!(
2393                     "{} and {last}",
2394                     types_and_spans[..types_and_spans.len() - 1]
2395                         .iter()
2396                         .map(|(x, _)| x.as_str())
2397                         .intersperse(&", ")
2398                         .collect::<String>()
2399                 ),
2400                 [(only, _)] => only.to_string(),
2401                 [] => "this type".to_string(),
2402             };
2403
2404             let arg_spans: Vec<Span> = args.map(|arg| arg.span()).collect();
2405
2406             let mut kinds = Vec::with_capacity(4);
2407             if lt {
2408                 kinds.push("lifetime");
2409             }
2410             if ty {
2411                 kinds.push("type");
2412             }
2413             if ct {
2414                 kinds.push("const");
2415             }
2416             if inf {
2417                 kinds.push("generic");
2418             }
2419             let (kind, s) = match kinds[..] {
2420                 [.., _, last] => (
2421                     format!(
2422                         "{} and {last}",
2423                         kinds[..kinds.len() - 1]
2424                             .iter()
2425                             .map(|&x| x)
2426                             .intersperse(", ")
2427                             .collect::<String>()
2428                     ),
2429                     "s",
2430                 ),
2431                 [only] => (only.to_string(), ""),
2432                 [] => unreachable!(),
2433             };
2434             let last_span = *arg_spans.last().unwrap();
2435             let span: MultiSpan = arg_spans.into();
2436             let mut err = struct_span_err!(
2437                 self.tcx().sess,
2438                 span,
2439                 E0109,
2440                 "{kind} arguments are not allowed on {this_type}",
2441             );
2442             err.span_label(last_span, format!("{kind} argument{s} not allowed"));
2443             for (what, span) in types_and_spans {
2444                 err.span_label(span, format!("not allowed on {what}"));
2445             }
2446             extend(&mut err);
2447             err.emit();
2448             emitted = true;
2449         }
2450
2451         for segment in segments {
2452             // Only emit the first error to avoid overloading the user with error messages.
2453             if let Some(b) = segment.args().bindings.first() {
2454                 prohibit_assoc_ty_binding(self.tcx(), b.span);
2455                 return true;
2456             }
2457         }
2458         emitted
2459     }
2460
2461     // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2462     pub fn def_ids_for_value_path_segments(
2463         &self,
2464         segments: &[hir::PathSegment<'_>],
2465         self_ty: Option<Ty<'tcx>>,
2466         kind: DefKind,
2467         def_id: DefId,
2468         span: Span,
2469     ) -> Vec<PathSeg> {
2470         // We need to extract the type parameters supplied by the user in
2471         // the path `path`. Due to the current setup, this is a bit of a
2472         // tricky-process; the problem is that resolve only tells us the
2473         // end-point of the path resolution, and not the intermediate steps.
2474         // Luckily, we can (at least for now) deduce the intermediate steps
2475         // just from the end-point.
2476         //
2477         // There are basically five cases to consider:
2478         //
2479         // 1. Reference to a constructor of a struct:
2480         //
2481         //        struct Foo<T>(...)
2482         //
2483         //    In this case, the parameters are declared in the type space.
2484         //
2485         // 2. Reference to a constructor of an enum variant:
2486         //
2487         //        enum E<T> { Foo(...) }
2488         //
2489         //    In this case, the parameters are defined in the type space,
2490         //    but may be specified either on the type or the variant.
2491         //
2492         // 3. Reference to a fn item or a free constant:
2493         //
2494         //        fn foo<T>() { }
2495         //
2496         //    In this case, the path will again always have the form
2497         //    `a::b::foo::<T>` where only the final segment should have
2498         //    type parameters. However, in this case, those parameters are
2499         //    declared on a value, and hence are in the `FnSpace`.
2500         //
2501         // 4. Reference to a method or an associated constant:
2502         //
2503         //        impl<A> SomeStruct<A> {
2504         //            fn foo<B>(...)
2505         //        }
2506         //
2507         //    Here we can have a path like
2508         //    `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2509         //    may appear in two places. The penultimate segment,
2510         //    `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2511         //    final segment, `foo::<B>` contains parameters in fn space.
2512         //
2513         // The first step then is to categorize the segments appropriately.
2514
2515         let tcx = self.tcx();
2516
2517         assert!(!segments.is_empty());
2518         let last = segments.len() - 1;
2519
2520         let mut path_segs = vec![];
2521
2522         match kind {
2523             // Case 1. Reference to a struct constructor.
2524             DefKind::Ctor(CtorOf::Struct, ..) => {
2525                 // Everything but the final segment should have no
2526                 // parameters at all.
2527                 let generics = tcx.generics_of(def_id);
2528                 // Variant and struct constructors use the
2529                 // generics of their parent type definition.
2530                 let generics_def_id = generics.parent.unwrap_or(def_id);
2531                 path_segs.push(PathSeg(generics_def_id, last));
2532             }
2533
2534             // Case 2. Reference to a variant constructor.
2535             DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2536                 let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2537                     let adt_def = self.probe_adt(span, self_ty).unwrap();
2538                     debug_assert!(adt_def.is_enum());
2539                     (adt_def.did(), last)
2540                 } else if last >= 1 && segments[last - 1].args.is_some() {
2541                     // Everything but the penultimate segment should have no
2542                     // parameters at all.
2543                     let mut def_id = def_id;
2544
2545                     // `DefKind::Ctor` -> `DefKind::Variant`
2546                     if let DefKind::Ctor(..) = kind {
2547                         def_id = tcx.parent(def_id);
2548                     }
2549
2550                     // `DefKind::Variant` -> `DefKind::Enum`
2551                     let enum_def_id = tcx.parent(def_id);
2552                     (enum_def_id, last - 1)
2553                 } else {
2554                     // FIXME: lint here recommending `Enum::<...>::Variant` form
2555                     // instead of `Enum::Variant::<...>` form.
2556
2557                     // Everything but the final segment should have no
2558                     // parameters at all.
2559                     let generics = tcx.generics_of(def_id);
2560                     // Variant and struct constructors use the
2561                     // generics of their parent type definition.
2562                     (generics.parent.unwrap_or(def_id), last)
2563                 };
2564                 path_segs.push(PathSeg(generics_def_id, index));
2565             }
2566
2567             // Case 3. Reference to a top-level value.
2568             DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static(_) => {
2569                 path_segs.push(PathSeg(def_id, last));
2570             }
2571
2572             // Case 4. Reference to a method or associated const.
2573             DefKind::AssocFn | DefKind::AssocConst => {
2574                 if segments.len() >= 2 {
2575                     let generics = tcx.generics_of(def_id);
2576                     path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2577                 }
2578                 path_segs.push(PathSeg(def_id, last));
2579             }
2580
2581             kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2582         }
2583
2584         debug!("path_segs = {:?}", path_segs);
2585
2586         path_segs
2587     }
2588
2589     /// Check a type `Path` and convert it to a `Ty`.
2590     pub fn res_to_ty(
2591         &self,
2592         opt_self_ty: Option<Ty<'tcx>>,
2593         path: &hir::Path<'_>,
2594         permit_variants: bool,
2595     ) -> Ty<'tcx> {
2596         let tcx = self.tcx();
2597
2598         debug!(
2599             "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2600             path.res, opt_self_ty, path.segments
2601         );
2602
2603         let span = path.span;
2604         match path.res {
2605             Res::Def(DefKind::OpaqueTy | DefKind::ImplTraitPlaceholder, did) => {
2606                 // Check for desugared `impl Trait`.
2607                 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2608                 let item_segment = path.segments.split_last().unwrap();
2609                 self.prohibit_generics(item_segment.1.iter(), |err| {
2610                     err.note("`impl Trait` types can't have type parameters");
2611                 });
2612                 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2613                 tcx.mk_opaque(did, substs)
2614             }
2615             Res::Def(
2616                 DefKind::Enum
2617                 | DefKind::TyAlias
2618                 | DefKind::Struct
2619                 | DefKind::Union
2620                 | DefKind::ForeignTy,
2621                 did,
2622             ) => {
2623                 assert_eq!(opt_self_ty, None);
2624                 self.prohibit_generics(path.segments.split_last().unwrap().1.iter(), |_| {});
2625                 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2626             }
2627             Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2628                 // Convert "variant type" as if it were a real type.
2629                 // The resulting `Ty` is type of the variant's enum for now.
2630                 assert_eq!(opt_self_ty, None);
2631
2632                 let path_segs =
2633                     self.def_ids_for_value_path_segments(path.segments, None, kind, def_id, span);
2634                 let generic_segs: FxHashSet<_> =
2635                     path_segs.iter().map(|PathSeg(_, index)| index).collect();
2636                 self.prohibit_generics(
2637                     path.segments.iter().enumerate().filter_map(|(index, seg)| {
2638                         if !generic_segs.contains(&index) { Some(seg) } else { None }
2639                     }),
2640                     |err| {
2641                         err.note("enum variants can't have type parameters");
2642                     },
2643                 );
2644
2645                 let PathSeg(def_id, index) = path_segs.last().unwrap();
2646                 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2647             }
2648             Res::Def(DefKind::TyParam, def_id) => {
2649                 assert_eq!(opt_self_ty, None);
2650                 self.prohibit_generics(path.segments.iter(), |err| {
2651                     if let Some(span) = tcx.def_ident_span(def_id) {
2652                         let name = tcx.item_name(def_id);
2653                         err.span_note(span, &format!("type parameter `{name}` defined here"));
2654                     }
2655                 });
2656
2657                 let def_id = def_id.expect_local();
2658                 let item_def_id = tcx.hir().ty_param_owner(def_id);
2659                 let generics = tcx.generics_of(item_def_id);
2660                 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2661                 tcx.mk_ty_param(index, tcx.hir().ty_param_name(def_id))
2662             }
2663             Res::SelfTyParam { .. } => {
2664                 // `Self` in trait or type alias.
2665                 assert_eq!(opt_self_ty, None);
2666                 self.prohibit_generics(path.segments.iter(), |err| {
2667                     if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments[..] {
2668                         err.span_suggestion_verbose(
2669                             ident.span.shrink_to_hi().to(args.span_ext),
2670                             "the `Self` type doesn't accept type parameters",
2671                             "",
2672                             Applicability::MaybeIncorrect,
2673                         );
2674                     }
2675                 });
2676                 tcx.types.self_param
2677             }
2678             Res::SelfTyAlias { alias_to: def_id, forbid_generic, .. } => {
2679                 // `Self` in impl (we know the concrete type).
2680                 assert_eq!(opt_self_ty, None);
2681                 // Try to evaluate any array length constants.
2682                 let ty = tcx.at(span).type_of(def_id);
2683                 let span_of_impl = tcx.span_of_impl(def_id);
2684                 self.prohibit_generics(path.segments.iter(), |err| {
2685                     let def_id = match *ty.kind() {
2686                         ty::Adt(self_def, _) => self_def.did(),
2687                         _ => return,
2688                     };
2689
2690                     let type_name = tcx.item_name(def_id);
2691                     let span_of_ty = tcx.def_ident_span(def_id);
2692                     let generics = tcx.generics_of(def_id).count();
2693
2694                     let msg = format!("`Self` is of type `{ty}`");
2695                     if let (Ok(i_sp), Some(t_sp)) = (span_of_impl, span_of_ty) {
2696                         let mut span: MultiSpan = vec![t_sp].into();
2697                         span.push_span_label(
2698                             i_sp,
2699                             &format!("`Self` is on type `{type_name}` in this `impl`"),
2700                         );
2701                         let mut postfix = "";
2702                         if generics == 0 {
2703                             postfix = ", which doesn't have generic parameters";
2704                         }
2705                         span.push_span_label(
2706                             t_sp,
2707                             &format!("`Self` corresponds to this type{postfix}"),
2708                         );
2709                         err.span_note(span, &msg);
2710                     } else {
2711                         err.note(&msg);
2712                     }
2713                     for segment in path.segments {
2714                         if let Some(args) = segment.args && segment.ident.name == kw::SelfUpper {
2715                             if generics == 0 {
2716                                 // FIXME(estebank): we could also verify that the arguments being
2717                                 // work for the `enum`, instead of just looking if it takes *any*.
2718                                 err.span_suggestion_verbose(
2719                                     segment.ident.span.shrink_to_hi().to(args.span_ext),
2720                                     "the `Self` type doesn't accept type parameters",
2721                                     "",
2722                                     Applicability::MachineApplicable,
2723                                 );
2724                                 return;
2725                             } else {
2726                                 err.span_suggestion_verbose(
2727                                     segment.ident.span,
2728                                     format!(
2729                                         "the `Self` type doesn't accept type parameters, use the \
2730                                         concrete type's name `{type_name}` instead if you want to \
2731                                         specify its type parameters"
2732                                     ),
2733                                     type_name,
2734                                     Applicability::MaybeIncorrect,
2735                                 );
2736                             }
2737                         }
2738                     }
2739                 });
2740                 // HACK(min_const_generics): Forbid generic `Self` types
2741                 // here as we can't easily do that during nameres.
2742                 //
2743                 // We do this before normalization as we otherwise allow
2744                 // ```rust
2745                 // trait AlwaysApplicable { type Assoc; }
2746                 // impl<T: ?Sized> AlwaysApplicable for T { type Assoc = usize; }
2747                 //
2748                 // trait BindsParam<T> {
2749                 //     type ArrayTy;
2750                 // }
2751                 // impl<T> BindsParam<T> for <T as AlwaysApplicable>::Assoc {
2752                 //    type ArrayTy = [u8; Self::MAX];
2753                 // }
2754                 // ```
2755                 // Note that the normalization happens in the param env of
2756                 // the anon const, which is empty. This is why the
2757                 // `AlwaysApplicable` impl needs a `T: ?Sized` bound for
2758                 // this to compile if we were to normalize here.
2759                 if forbid_generic && ty.needs_subst() {
2760                     let mut err = tcx.sess.struct_span_err(
2761                         path.span,
2762                         "generic `Self` types are currently not permitted in anonymous constants",
2763                     );
2764                     if let Some(hir::Node::Item(&hir::Item {
2765                         kind: hir::ItemKind::Impl(ref impl_),
2766                         ..
2767                     })) = tcx.hir().get_if_local(def_id)
2768                     {
2769                         err.span_note(impl_.self_ty.span, "not a concrete type");
2770                     }
2771                     tcx.ty_error_with_guaranteed(err.emit())
2772                 } else {
2773                     ty
2774                 }
2775             }
2776             Res::Def(DefKind::AssocTy, def_id) => {
2777                 debug_assert!(path.segments.len() >= 2);
2778                 self.prohibit_generics(path.segments[..path.segments.len() - 2].iter(), |_| {});
2779                 // HACK: until we support `<Type as ~const Trait>`, assume all of them are.
2780                 let constness = if tcx.has_attr(tcx.parent(def_id), sym::const_trait) {
2781                     ty::BoundConstness::ConstIfConst
2782                 } else {
2783                     ty::BoundConstness::NotConst
2784                 };
2785                 self.qpath_to_ty(
2786                     span,
2787                     opt_self_ty,
2788                     def_id,
2789                     &path.segments[path.segments.len() - 2],
2790                     path.segments.last().unwrap(),
2791                     constness,
2792                 )
2793             }
2794             Res::PrimTy(prim_ty) => {
2795                 assert_eq!(opt_self_ty, None);
2796                 self.prohibit_generics(path.segments.iter(), |err| {
2797                     let name = prim_ty.name_str();
2798                     for segment in path.segments {
2799                         if let Some(args) = segment.args {
2800                             err.span_suggestion_verbose(
2801                                 segment.ident.span.shrink_to_hi().to(args.span_ext),
2802                                 &format!("primitive type `{name}` doesn't have generic parameters"),
2803                                 "",
2804                                 Applicability::MaybeIncorrect,
2805                             );
2806                         }
2807                     }
2808                 });
2809                 match prim_ty {
2810                     hir::PrimTy::Bool => tcx.types.bool,
2811                     hir::PrimTy::Char => tcx.types.char,
2812                     hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2813                     hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2814                     hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2815                     hir::PrimTy::Str => tcx.types.str_,
2816                 }
2817             }
2818             Res::Err => {
2819                 let e = self
2820                     .tcx()
2821                     .sess
2822                     .delay_span_bug(path.span, "path with `Res::Err` but no error emitted");
2823                 self.set_tainted_by_errors(e);
2824                 self.tcx().ty_error_with_guaranteed(e)
2825             }
2826             _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2827         }
2828     }
2829
2830     /// Parses the programmer's textual representation of a type into our
2831     /// internal notion of a type.
2832     pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2833         self.ast_ty_to_ty_inner(ast_ty, false, false)
2834     }
2835
2836     /// Parses the programmer's textual representation of a type into our
2837     /// internal notion of a type.  This is meant to be used within a path.
2838     pub fn ast_ty_to_ty_in_path(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2839         self.ast_ty_to_ty_inner(ast_ty, false, true)
2840     }
2841
2842     /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2843     /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2844     #[instrument(level = "debug", skip(self), ret)]
2845     fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool, in_path: bool) -> Ty<'tcx> {
2846         let tcx = self.tcx();
2847
2848         let result_ty = match ast_ty.kind {
2849             hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(ty)),
2850             hir::TyKind::Ptr(ref mt) => {
2851                 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl })
2852             }
2853             hir::TyKind::Ref(ref region, ref mt) => {
2854                 let r = self.ast_region_to_region(region, None);
2855                 debug!(?r);
2856                 let t = self.ast_ty_to_ty_inner(mt.ty, true, false);
2857                 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2858             }
2859             hir::TyKind::Never => tcx.types.never,
2860             hir::TyKind::Tup(fields) => tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(t))),
2861             hir::TyKind::BareFn(bf) => {
2862                 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span);
2863
2864                 tcx.mk_fn_ptr(self.ty_of_fn(
2865                     ast_ty.hir_id,
2866                     bf.unsafety,
2867                     bf.abi,
2868                     bf.decl,
2869                     None,
2870                     Some(ast_ty),
2871                 ))
2872             }
2873             hir::TyKind::TraitObject(bounds, ref lifetime, repr) => {
2874                 self.maybe_lint_bare_trait(ast_ty, in_path);
2875                 let repr = match repr {
2876                     TraitObjectSyntax::Dyn | TraitObjectSyntax::None => ty::Dyn,
2877                     TraitObjectSyntax::DynStar => ty::DynStar,
2878                 };
2879                 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed, repr)
2880             }
2881             hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2882                 debug!(?maybe_qself, ?path);
2883                 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2884                 self.res_to_ty(opt_self_ty, path, false)
2885             }
2886             hir::TyKind::OpaqueDef(item_id, lifetimes, in_trait) => {
2887                 let opaque_ty = tcx.hir().item(item_id);
2888                 let def_id = item_id.owner_id.to_def_id();
2889
2890                 match opaque_ty.kind {
2891                     hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
2892                         self.impl_trait_ty_to_ty(def_id, lifetimes, origin, in_trait)
2893                     }
2894                     ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2895                 }
2896             }
2897             hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2898                 debug!(?qself, ?segment);
2899                 let ty = self.ast_ty_to_ty_inner(qself, false, true);
2900                 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, qself, segment, false)
2901                     .map(|(ty, _, _)| ty)
2902                     .unwrap_or_else(|_| tcx.ty_error())
2903             }
2904             hir::TyKind::Path(hir::QPath::LangItem(lang_item, span, _)) => {
2905                 let def_id = tcx.require_lang_item(lang_item, Some(span));
2906                 let (substs, _) = self.create_substs_for_ast_path(
2907                     span,
2908                     def_id,
2909                     &[],
2910                     &hir::PathSegment::invalid(),
2911                     &GenericArgs::none(),
2912                     true,
2913                     None,
2914                     ty::BoundConstness::NotConst,
2915                 );
2916                 EarlyBinder(tcx.at(span).type_of(def_id)).subst(tcx, substs)
2917             }
2918             hir::TyKind::Array(ref ty, ref length) => {
2919                 let length = match length {
2920                     &hir::ArrayLen::Infer(_, span) => self.ct_infer(tcx.types.usize, None, span),
2921                     hir::ArrayLen::Body(constant) => {
2922                         ty::Const::from_anon_const(tcx, constant.def_id)
2923                     }
2924                 };
2925
2926                 tcx.mk_ty(ty::Array(self.ast_ty_to_ty(ty), length))
2927             }
2928             hir::TyKind::Typeof(ref e) => {
2929                 let ty_erased = tcx.type_of(e.def_id);
2930                 let ty = tcx.fold_regions(ty_erased, |r, _| {
2931                     if r.is_erased() { tcx.lifetimes.re_static } else { r }
2932                 });
2933                 let span = ast_ty.span;
2934                 tcx.sess.emit_err(TypeofReservedKeywordUsed {
2935                     span,
2936                     ty,
2937                     opt_sugg: Some((span, Applicability::MachineApplicable))
2938                         .filter(|_| ty.is_suggestable(tcx, false)),
2939                 });
2940
2941                 ty
2942             }
2943             hir::TyKind::Infer => {
2944                 // Infer also appears as the type of arguments or return
2945                 // values in an ExprKind::Closure, or as
2946                 // the type of local variables. Both of these cases are
2947                 // handled specially and will not descend into this routine.
2948                 self.ty_infer(None, ast_ty.span)
2949             }
2950             hir::TyKind::Err => tcx.ty_error(),
2951         };
2952
2953         self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2954         result_ty
2955     }
2956
2957     #[instrument(level = "debug", skip(self), ret)]
2958     fn impl_trait_ty_to_ty(
2959         &self,
2960         def_id: DefId,
2961         lifetimes: &[hir::GenericArg<'_>],
2962         origin: OpaqueTyOrigin,
2963         in_trait: bool,
2964     ) -> Ty<'tcx> {
2965         debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2966         let tcx = self.tcx();
2967
2968         let generics = tcx.generics_of(def_id);
2969
2970         debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2971         let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2972             if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2973                 // Our own parameters are the resolved lifetimes.
2974                 let GenericParamDefKind::Lifetime { .. } = param.kind else { bug!() };
2975                 let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] else { bug!() };
2976                 self.ast_region_to_region(lifetime, None).into()
2977             } else {
2978                 tcx.mk_param_from_def(param)
2979             }
2980         });
2981         debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2982
2983         if in_trait { tcx.mk_projection(def_id, substs) } else { tcx.mk_opaque(def_id, substs) }
2984     }
2985
2986     pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2987         match ty.kind {
2988             hir::TyKind::Infer if expected_ty.is_some() => {
2989                 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2990                 expected_ty.unwrap()
2991             }
2992             _ => self.ast_ty_to_ty(ty),
2993         }
2994     }
2995
2996     #[instrument(level = "debug", skip(self, hir_id, unsafety, abi, decl, generics, hir_ty), ret)]
2997     pub fn ty_of_fn(
2998         &self,
2999         hir_id: hir::HirId,
3000         unsafety: hir::Unsafety,
3001         abi: abi::Abi,
3002         decl: &hir::FnDecl<'_>,
3003         generics: Option<&hir::Generics<'_>>,
3004         hir_ty: Option<&hir::Ty<'_>>,
3005     ) -> ty::PolyFnSig<'tcx> {
3006         let tcx = self.tcx();
3007         let bound_vars = tcx.late_bound_vars(hir_id);
3008         debug!(?bound_vars);
3009
3010         // We proactively collect all the inferred type params to emit a single error per fn def.
3011         let mut visitor = HirPlaceholderCollector::default();
3012         let mut infer_replacements = vec![];
3013
3014         if let Some(generics) = generics {
3015             walk_generics(&mut visitor, generics);
3016         }
3017
3018         let input_tys: Vec<_> = decl
3019             .inputs
3020             .iter()
3021             .enumerate()
3022             .map(|(i, a)| {
3023                 if let hir::TyKind::Infer = a.kind && !self.allow_ty_infer() {
3024                     if let Some(suggested_ty) =
3025                         self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i))
3026                     {
3027                         infer_replacements.push((a.span, suggested_ty.to_string()));
3028                         return suggested_ty;
3029                     }
3030                 }
3031
3032                 // Only visit the type looking for `_` if we didn't fix the type above
3033                 visitor.visit_ty(a);
3034                 self.ty_of_arg(a, None)
3035             })
3036             .collect();
3037
3038         let output_ty = match decl.output {
3039             hir::FnRetTy::Return(output) => {
3040                 if let hir::TyKind::Infer = output.kind
3041                     && !self.allow_ty_infer()
3042                     && let Some(suggested_ty) =
3043                         self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, None)
3044                 {
3045                     infer_replacements.push((output.span, suggested_ty.to_string()));
3046                     suggested_ty
3047                 } else {
3048                     visitor.visit_ty(output);
3049                     self.ast_ty_to_ty(output)
3050                 }
3051             }
3052             hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
3053         };
3054
3055         debug!(?output_ty);
3056
3057         let fn_ty = tcx.mk_fn_sig(input_tys.into_iter(), output_ty, decl.c_variadic, unsafety, abi);
3058         let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3059
3060         if !self.allow_ty_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) {
3061             // We always collect the spans for placeholder types when evaluating `fn`s, but we
3062             // only want to emit an error complaining about them if infer types (`_`) are not
3063             // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
3064             // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
3065
3066             let mut diag = crate::collect::placeholder_type_error_diag(
3067                 tcx,
3068                 generics,
3069                 visitor.0,
3070                 infer_replacements.iter().map(|(s, _)| *s).collect(),
3071                 true,
3072                 hir_ty,
3073                 "function",
3074             );
3075
3076             if !infer_replacements.is_empty() {
3077                 diag.multipart_suggestion(
3078                     &format!(
3079                     "try replacing `_` with the type{} in the corresponding trait method signature",
3080                     rustc_errors::pluralize!(infer_replacements.len()),
3081                 ),
3082                     infer_replacements,
3083                     Applicability::MachineApplicable,
3084                 );
3085             }
3086
3087             diag.emit();
3088         }
3089
3090         // Find any late-bound regions declared in return type that do
3091         // not appear in the arguments. These are not well-formed.
3092         //
3093         // Example:
3094         //     for<'a> fn() -> &'a str <-- 'a is bad
3095         //     for<'a> fn(&'a String) -> &'a str <-- 'a is ok
3096         let inputs = bare_fn_ty.inputs();
3097         let late_bound_in_args =
3098             tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
3099         let output = bare_fn_ty.output();
3100         let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
3101
3102         self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3103             struct_span_err!(
3104                 tcx.sess,
3105                 decl.output.span(),
3106                 E0581,
3107                 "return type references {}, which is not constrained by the fn input types",
3108                 br_name
3109             )
3110         });
3111
3112         bare_fn_ty
3113     }
3114
3115     /// Given a fn_hir_id for a impl function, suggest the type that is found on the
3116     /// corresponding function in the trait that the impl implements, if it exists.
3117     /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
3118     /// corresponds to the return type.
3119     fn suggest_trait_fn_ty_for_impl_fn_infer(
3120         &self,
3121         fn_hir_id: hir::HirId,
3122         arg_idx: Option<usize>,
3123     ) -> Option<Ty<'tcx>> {
3124         let tcx = self.tcx();
3125         let hir = tcx.hir();
3126
3127         let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3128             hir.get(fn_hir_id) else { return None };
3129         let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(i), .. }) =
3130                 hir.get_parent(fn_hir_id) else { bug!("ImplItem should have Impl parent") };
3131
3132         let trait_ref = self.instantiate_mono_trait_ref(
3133             i.of_trait.as_ref()?,
3134             self.ast_ty_to_ty(i.self_ty),
3135             ty::BoundConstness::NotConst,
3136         );
3137
3138         let assoc = tcx.associated_items(trait_ref.def_id).find_by_name_and_kind(
3139             tcx,
3140             *ident,
3141             ty::AssocKind::Fn,
3142             trait_ref.def_id,
3143         )?;
3144
3145         let fn_sig = tcx.bound_fn_sig(assoc.def_id).subst(
3146             tcx,
3147             trait_ref.substs.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3148         );
3149
3150         let ty = if let Some(arg_idx) = arg_idx { fn_sig.input(arg_idx) } else { fn_sig.output() };
3151
3152         Some(tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), ty))
3153     }
3154
3155     #[instrument(level = "trace", skip(self, generate_err))]
3156     fn validate_late_bound_regions(
3157         &self,
3158         constrained_regions: FxHashSet<ty::BoundRegionKind>,
3159         referenced_regions: FxHashSet<ty::BoundRegionKind>,
3160         generate_err: impl Fn(&str) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
3161     ) {
3162         for br in referenced_regions.difference(&constrained_regions) {
3163             let br_name = match *br {
3164                 ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) | ty::BrEnv => {
3165                     "an anonymous lifetime".to_string()
3166                 }
3167                 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
3168             };
3169
3170             let mut err = generate_err(&br_name);
3171
3172             if let ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) = *br {
3173                 // The only way for an anonymous lifetime to wind up
3174                 // in the return type but **also** be unconstrained is
3175                 // if it only appears in "associated types" in the
3176                 // input. See #47511 and #62200 for examples. In this case,
3177                 // though we can easily give a hint that ought to be
3178                 // relevant.
3179                 err.note(
3180                     "lifetimes appearing in an associated or opaque type are not considered constrained",
3181                 );
3182                 err.note("consider introducing a named lifetime parameter");
3183             }
3184
3185             err.emit();
3186         }
3187     }
3188
3189     /// Given the bounds on an object, determines what single region bound (if any) we can
3190     /// use to summarize this type. The basic idea is that we will use the bound the user
3191     /// provided, if they provided one, and otherwise search the supertypes of trait bounds
3192     /// for region bounds. It may be that we can derive no bound at all, in which case
3193     /// we return `None`.
3194     fn compute_object_lifetime_bound(
3195         &self,
3196         span: Span,
3197         existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3198     ) -> Option<ty::Region<'tcx>> // if None, use the default
3199     {
3200         let tcx = self.tcx();
3201
3202         debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
3203
3204         // No explicit region bound specified. Therefore, examine trait
3205         // bounds and see if we can derive region bounds from those.
3206         let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3207
3208         // If there are no derived region bounds, then report back that we
3209         // can find no region bound. The caller will use the default.
3210         if derived_region_bounds.is_empty() {
3211             return None;
3212         }
3213
3214         // If any of the derived region bounds are 'static, that is always
3215         // the best choice.
3216         if derived_region_bounds.iter().any(|r| r.is_static()) {
3217             return Some(tcx.lifetimes.re_static);
3218         }
3219
3220         // Determine whether there is exactly one unique region in the set
3221         // of derived region bounds. If so, use that. Otherwise, report an
3222         // error.
3223         let r = derived_region_bounds[0];
3224         if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3225             tcx.sess.emit_err(AmbiguousLifetimeBound { span });
3226         }
3227         Some(r)
3228     }
3229
3230     /// Make sure that we are in the condition to suggest the blanket implementation.
3231     fn maybe_lint_blanket_trait_impl(&self, self_ty: &hir::Ty<'_>, diag: &mut Diagnostic) {
3232         let tcx = self.tcx();
3233         let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
3234         if let hir::Node::Item(hir::Item {
3235             kind:
3236                 hir::ItemKind::Impl(hir::Impl {
3237                     self_ty: impl_self_ty, of_trait: Some(of_trait_ref), generics, ..
3238                 }),
3239             ..
3240         }) = tcx.hir().get_by_def_id(parent_id) && self_ty.hir_id == impl_self_ty.hir_id
3241         {
3242             if !of_trait_ref.trait_def_id().map_or(false, |def_id| def_id.is_local()) {
3243                 return;
3244             }
3245             let of_trait_span = of_trait_ref.path.span;
3246             // make sure that we are not calling unwrap to abort during the compilation
3247             let Ok(impl_trait_name) = tcx.sess.source_map().span_to_snippet(self_ty.span) else { return; };
3248             let Ok(of_trait_name) = tcx.sess.source_map().span_to_snippet(of_trait_span) else { return; };
3249             // check if the trait has generics, to make a correct suggestion
3250             let param_name = generics.params.next_type_param_name(None);
3251
3252             let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() {
3253                 (span, format!(", {}: {}", param_name, impl_trait_name))
3254             } else {
3255                 (generics.span, format!("<{}: {}>", param_name, impl_trait_name))
3256             };
3257             diag.multipart_suggestion(
3258             format!("alternatively use a blanket \
3259                      implementation to implement `{of_trait_name}` for \
3260                      all types that also implement `{impl_trait_name}`"),
3261                 vec![
3262                     (self_ty.span, param_name),
3263                     add_generic_sugg,
3264                 ],
3265                 Applicability::MaybeIncorrect,
3266             );
3267         }
3268     }
3269
3270     fn maybe_lint_bare_trait(&self, self_ty: &hir::Ty<'_>, in_path: bool) {
3271         let tcx = self.tcx();
3272         if let hir::TyKind::TraitObject([poly_trait_ref, ..], _, TraitObjectSyntax::None) =
3273             self_ty.kind
3274         {
3275             let needs_bracket = in_path
3276                 && !tcx
3277                     .sess
3278                     .source_map()
3279                     .span_to_prev_source(self_ty.span)
3280                     .ok()
3281                     .map_or(false, |s| s.trim_end().ends_with('<'));
3282
3283             let is_global = poly_trait_ref.trait_ref.path.is_global();
3284
3285             let mut sugg = Vec::from_iter([(
3286                 self_ty.span.shrink_to_lo(),
3287                 format!(
3288                     "{}dyn {}",
3289                     if needs_bracket { "<" } else { "" },
3290                     if is_global { "(" } else { "" },
3291                 ),
3292             )]);
3293
3294             if is_global || needs_bracket {
3295                 sugg.push((
3296                     self_ty.span.shrink_to_hi(),
3297                     format!(
3298                         "{}{}",
3299                         if is_global { ")" } else { "" },
3300                         if needs_bracket { ">" } else { "" },
3301                     ),
3302                 ));
3303             }
3304
3305             if self_ty.span.edition() >= Edition::Edition2021 {
3306                 let msg = "trait objects must include the `dyn` keyword";
3307                 let label = "add `dyn` keyword before this trait";
3308                 let mut diag =
3309                     rustc_errors::struct_span_err!(tcx.sess, self_ty.span, E0782, "{}", msg);
3310                 if self_ty.span.can_be_used_for_suggestions() {
3311                     diag.multipart_suggestion_verbose(
3312                         label,
3313                         sugg,
3314                         Applicability::MachineApplicable,
3315                     );
3316                 }
3317                 // check if the impl trait that we are considering is a impl of a local trait
3318                 self.maybe_lint_blanket_trait_impl(&self_ty, &mut diag);
3319                 diag.emit();
3320             } else {
3321                 let msg = "trait objects without an explicit `dyn` are deprecated";
3322                 tcx.struct_span_lint_hir(
3323                     BARE_TRAIT_OBJECTS,
3324                     self_ty.hir_id,
3325                     self_ty.span,
3326                     msg,
3327                     |lint| {
3328                         lint.multipart_suggestion_verbose(
3329                             "use `dyn`",
3330                             sugg,
3331                             Applicability::MachineApplicable,
3332                         );
3333                         self.maybe_lint_blanket_trait_impl(&self_ty, lint);
3334                         lint
3335                     },
3336                 );
3337             }
3338         }
3339     }
3340 }