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