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