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