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