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`.
8 use crate::bounds::Bounds;
9 use crate::collect::PlaceholderHirTyCollector;
11 AmbiguousLifetimeBound, MultipleRelaxedDefaultBounds, TraitObjectDeclaredWithNoTraits,
12 TypeofReservedKeywordUsed, ValueOfAssociatedStructAlreadySpecified,
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};
19 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
20 use rustc_hir::def_id::{DefId, LocalDefId};
21 use rustc_hir::intravisit::{walk_generics, Visitor as _};
22 use rustc_hir::lang_items::LangItem;
23 use rustc_hir::{GenericArg, GenericArgs};
24 use rustc_middle::ty::subst::{self, GenericArgKind, InternalSubsts, Subst, SubstsRef};
25 use rustc_middle::ty::GenericParamDefKind;
26 use rustc_middle::ty::{self, Const, DefIdTree, Ty, TyCtxt, TypeFoldable};
27 use rustc_session::lint::builtin::AMBIGUOUS_ASSOCIATED_ITEMS;
28 use rustc_span::lev_distance::find_best_match_for_name;
29 use rustc_span::symbol::{Ident, Symbol};
30 use rustc_span::{Span, DUMMY_SP};
31 use rustc_target::spec::abi;
32 use rustc_trait_selection::traits;
33 use rustc_trait_selection::traits::astconv_object_safety_violations;
34 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
35 use rustc_trait_selection::traits::wf::object_region_bounds;
37 use smallvec::SmallVec;
39 use std::collections::BTreeSet;
43 pub struct PathSeg(pub DefId, pub usize);
45 pub trait AstConv<'tcx> {
46 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
48 fn item_def_id(&self) -> Option<DefId>;
50 /// Returns predicates in scope of the form `X: Foo<T>`, where `X`
51 /// is a type parameter `X` with the given id `def_id` and T
52 /// matches `assoc_name`. This is a subset of the full set of
55 /// This is used for one specific purpose: resolving "short-hand"
56 /// associated type references like `T::Item`. In principle, we
57 /// would do that by first getting the full set of predicates in
58 /// scope and then filtering down to find those that apply to `T`,
59 /// but this can lead to cycle errors. The problem is that we have
60 /// to do this resolution *in order to create the predicates in
61 /// the first place*. Hence, we have this "special pass".
62 fn get_type_parameter_bounds(
67 ) -> ty::GenericPredicates<'tcx>;
69 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
70 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
71 -> Option<ty::Region<'tcx>>;
73 /// Returns the type to use when a type is omitted.
74 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
76 /// Returns `true` if `_` is allowed in type signatures in the current context.
77 fn allow_ty_infer(&self) -> bool;
79 /// Returns the const to use when a const is omitted.
83 param: Option<&ty::GenericParamDef>,
85 ) -> &'tcx Const<'tcx>;
87 /// Projecting an associated type from a (potentially)
88 /// higher-ranked trait reference is more complicated, because of
89 /// the possibility of late-bound regions appearing in the
90 /// associated type binding. This is not legal in function
91 /// signatures for that reason. In a function body, we can always
92 /// handle it because we can use inference variables to remove the
93 /// late-bound regions.
94 fn projected_ty_from_poly_trait_ref(
98 item_segment: &hir::PathSegment<'_>,
99 poly_trait_ref: ty::PolyTraitRef<'tcx>,
102 /// Normalize an associated type coming from the user.
103 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
105 /// Invoked when we encounter an error from some prior pass
106 /// (e.g., resolve) that is translated into a ty-error. This is
107 /// used to help suppress derived errors typeck might otherwise
109 fn set_tainted_by_errors(&self);
111 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
115 struct ConvertedBinding<'a, 'tcx> {
118 kind: ConvertedBindingKind<'a, 'tcx>,
119 gen_args: &'a GenericArgs<'a>,
124 enum ConvertedBindingKind<'a, 'tcx> {
126 Constraint(&'a [hir::GenericBound<'a>]),
129 /// New-typed boolean indicating whether explicit late-bound lifetimes
130 /// are present in a set of generic arguments.
132 /// For example if we have some method `fn f<'a>(&'a self)` implemented
133 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
134 /// is late-bound so should not be provided explicitly. Thus, if `f` is
135 /// instantiated with some generic arguments providing `'a` explicitly,
136 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
137 /// can provide an appropriate diagnostic later.
138 #[derive(Copy, Clone, PartialEq)]
139 pub enum ExplicitLateBound {
144 #[derive(Copy, Clone, PartialEq)]
145 pub enum IsMethodCall {
150 /// Denotes the "position" of a generic argument, indicating if it is a generic type,
151 /// generic function or generic method call.
152 #[derive(Copy, Clone, PartialEq)]
153 pub(crate) enum GenericArgPosition {
155 Value, // e.g., functions
159 /// A marker denoting that the generic arguments that were
160 /// provided did not match the respective generic parameters.
161 #[derive(Clone, Default)]
162 pub struct GenericArgCountMismatch {
163 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
164 pub reported: Option<ErrorReported>,
165 /// A list of spans of arguments provided that were not valid.
166 pub invalid_args: Vec<Span>,
169 /// Decorates the result of a generic argument count mismatch
170 /// check with whether explicit late bounds were provided.
172 pub struct GenericArgCountResult {
173 pub explicit_late_bound: ExplicitLateBound,
174 pub correct: Result<(), GenericArgCountMismatch>,
177 pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> {
178 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
182 param: &ty::GenericParamDef,
183 arg: &GenericArg<'_>,
184 ) -> subst::GenericArg<'tcx>;
188 substs: Option<&[subst::GenericArg<'tcx>]>,
189 param: &ty::GenericParamDef,
191 ) -> subst::GenericArg<'tcx>;
194 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
195 #[tracing::instrument(level = "debug", skip(self))]
196 pub fn ast_region_to_region(
198 lifetime: &hir::Lifetime,
199 def: Option<&ty::GenericParamDef>,
200 ) -> ty::Region<'tcx> {
201 let tcx = self.tcx();
202 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
204 let r = match tcx.named_region(lifetime.hir_id) {
205 Some(rl::Region::Static) => tcx.lifetimes.re_static,
207 Some(rl::Region::LateBound(debruijn, index, def_id, _)) => {
208 let name = lifetime_name(def_id.expect_local());
209 let br = ty::BoundRegion {
210 var: ty::BoundVar::from_u32(index),
211 kind: ty::BrNamed(def_id, name),
213 tcx.mk_region(ty::ReLateBound(debruijn, br))
216 Some(rl::Region::LateBoundAnon(debruijn, index, anon_index)) => {
217 let br = ty::BoundRegion {
218 var: ty::BoundVar::from_u32(index),
219 kind: ty::BrAnon(anon_index),
221 tcx.mk_region(ty::ReLateBound(debruijn, br))
224 Some(rl::Region::EarlyBound(index, id, _)) => {
225 let name = lifetime_name(id.expect_local());
226 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
229 Some(rl::Region::Free(scope, id)) => {
230 let name = lifetime_name(id.expect_local());
231 tcx.mk_region(ty::ReFree(ty::FreeRegion {
233 bound_region: ty::BrNamed(id, name),
236 // (*) -- not late-bound, won't change
240 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
241 debug!(?lifetime, "unelided lifetime in signature");
243 // This indicates an illegal lifetime
244 // elision. `resolve_lifetime` should have
245 // reported an error in this case -- but if
246 // not, let's error out.
247 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
249 // Supply some dummy value. We don't have an
250 // `re_error`, annoyingly, so use `'static`.
251 tcx.lifetimes.re_static
256 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
261 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
262 /// returns an appropriate set of substitutions for this particular reference to `I`.
263 pub fn ast_path_substs_for_ty(
267 item_segment: &hir::PathSegment<'_>,
268 ) -> SubstsRef<'tcx> {
269 let (substs, _) = self.create_substs_for_ast_path(
275 item_segment.infer_args,
278 let assoc_bindings = self.create_assoc_bindings_for_generic_args(item_segment.args());
280 if let Some(b) = assoc_bindings.first() {
281 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
287 /// Given the type/lifetime/const arguments provided to some path (along with
288 /// an implicit `Self`, if this is a trait reference), returns the complete
289 /// set of substitutions. This may involve applying defaulted type parameters.
290 /// Also returns back constraints on associated types.
295 /// T: std::ops::Index<usize, Output = u32>
296 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
299 /// 1. The `self_ty` here would refer to the type `T`.
300 /// 2. The path in question is the path to the trait `std::ops::Index`,
301 /// which will have been resolved to a `def_id`
302 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
303 /// parameters are returned in the `SubstsRef`, the associated type bindings like
304 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
306 /// Note that the type listing given here is *exactly* what the user provided.
308 /// For (generic) associated types
311 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
314 /// We have the parent substs are the substs for the parent trait:
315 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
316 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
317 /// lists: `[Vec<u8>, u8, 'a]`.
318 #[tracing::instrument(level = "debug", skip(self, span))]
319 fn create_substs_for_ast_path<'a>(
323 parent_substs: &[subst::GenericArg<'tcx>],
324 seg: &hir::PathSegment<'_>,
325 generic_args: &'a hir::GenericArgs<'_>,
327 self_ty: Option<Ty<'tcx>>,
328 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
329 // If the type is parameterized by this region, then replace this
330 // region with the current anon region binding (in other words,
331 // whatever & would get replaced with).
333 let tcx = self.tcx();
334 let generics = tcx.generics_of(def_id);
335 debug!("generics: {:?}", generics);
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())
343 // This item (presumably a trait) needs a self-type.
344 assert!(self_ty.is_some());
347 assert!(self_ty.is_none() && parent_substs.is_empty());
350 let arg_count = Self::check_generic_arg_count(
357 GenericArgPosition::Type,
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(&[]), arg_count);
370 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
372 struct SubstsForAstPathCtxt<'a, 'tcx> {
373 astconv: &'a (dyn AstConv<'tcx> + 'a),
375 generic_args: &'a GenericArgs<'a>,
377 missing_type_params: Vec<String>,
378 inferred_params: Vec<Span>,
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(tcx).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.
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)
407 // The last component of this tuple is unimportant.
414 param: &ty::GenericParamDef,
415 arg: &GenericArg<'_>,
416 ) -> subst::GenericArg<'tcx> {
417 let tcx = self.astconv.tcx();
418 match (¶m.kind, arg) {
419 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
420 self.astconv.ast_region_to_region(<, Some(param)).into()
422 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
424 tcx.check_optional_stability(
430 // Default generic parameters may not be marked
431 // with stability attributes, i.e. when the
432 // default parameter was defined at the same time
433 // as the rest of the type. As such, we ignore missing
434 // stability attributes.
438 if let (hir::TyKind::Infer, false) =
439 (&ty.kind, self.astconv.allow_ty_infer())
441 self.inferred_params.push(ty.span);
442 tcx.ty_error().into()
444 self.astconv.ast_ty_to_ty(&ty).into()
447 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
448 ty::Const::from_opt_const_arg_anon_const(
450 ty::WithOptConstParam {
451 did: tcx.hir().local_def_id(ct.value.hir_id),
452 const_param_did: Some(param.def_id),
457 (&GenericParamDefKind::Const { has_default }, hir::GenericArg::Infer(inf)) => {
459 tcx.const_param_default(param.def_id).into()
460 } else if self.astconv.allow_ty_infer() {
461 // FIXME(const_generics): Actually infer parameter here?
464 self.inferred_params.push(inf.span);
465 tcx.ty_error().into()
469 &GenericParamDefKind::Type { has_default, .. },
470 hir::GenericArg::Infer(inf),
473 tcx.check_optional_stability(
479 // Default generic parameters may not be marked
480 // with stability attributes, i.e. when the
481 // default parameter was defined at the same time
482 // as the rest of the type. As such, we ignore missing
483 // stability attributes.
487 if self.astconv.allow_ty_infer() {
488 self.astconv.ast_ty_to_ty(&inf.to_ty()).into()
490 self.inferred_params.push(inf.span);
491 tcx.ty_error().into()
500 substs: Option<&[subst::GenericArg<'tcx>]>,
501 param: &ty::GenericParamDef,
503 ) -> subst::GenericArg<'tcx> {
504 let tcx = self.astconv.tcx();
506 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
507 GenericParamDefKind::Type { has_default, .. } => {
508 if !infer_args && has_default {
509 // No type parameter provided, but a default exists.
511 // If we are converting an object type, then the
512 // `Self` parameter is unknown. However, some of the
513 // other type parameters may reference `Self` in their
514 // defaults. This will lead to an ICE if we are not
516 if self.default_needs_object_self(param) {
517 self.missing_type_params.push(param.name.to_string());
518 tcx.ty_error().into()
520 // This is a default type parameter.
521 let substs = substs.unwrap();
522 if substs.iter().any(|arg| match arg.unpack() {
523 GenericArgKind::Type(ty) => ty.references_error(),
526 // Avoid ICE #86756 when type error recovery goes awry.
527 return tcx.ty_error().into();
532 tcx.at(self.span).type_of(param.def_id).subst_spanned(
540 } else if infer_args {
541 // No type parameters were provided, we can infer all.
542 let param = if !self.default_needs_object_self(param) {
547 self.astconv.ty_infer(param, self.span).into()
549 // We've already errored above about the mismatch.
550 tcx.ty_error().into()
553 GenericParamDefKind::Const { has_default } => {
554 let ty = tcx.at(self.span).type_of(param.def_id);
555 if !infer_args && has_default {
556 tcx.const_param_default(param.def_id)
557 .subst_spanned(tcx, substs.unwrap(), Some(self.span))
561 self.astconv.ct_infer(ty, Some(param), self.span).into()
563 // We've already errored above about the mismatch.
564 tcx.const_error(ty).into()
572 let mut substs_ctx = SubstsForAstPathCtxt {
577 missing_type_params: vec![],
578 inferred_params: vec![],
582 let substs = Self::create_substs_for_generic_args(
592 self.complain_about_missing_type_params(
593 substs_ctx.missing_type_params,
596 generic_args.args.is_empty(),
600 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
601 generics, self_ty, substs
607 fn create_assoc_bindings_for_generic_args<'a>(
609 generic_args: &'a hir::GenericArgs<'_>,
610 ) -> Vec<ConvertedBinding<'a, 'tcx>> {
611 // Convert associated-type bindings or constraints into a separate vector.
612 // Example: Given this:
614 // T: Iterator<Item = u32>
616 // The `T` is passed in as a self-type; the `Item = u32` is
617 // not a "type parameter" of the `Iterator` trait, but rather
618 // a restriction on `<T as Iterator>::Item`, so it is passed
620 let assoc_bindings = generic_args
624 let kind = match binding.kind {
625 hir::TypeBindingKind::Equality { ref ty } => {
626 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
628 hir::TypeBindingKind::Constraint { ref bounds } => {
629 ConvertedBindingKind::Constraint(bounds)
633 hir_id: binding.hir_id,
634 item_name: binding.ident,
636 gen_args: binding.gen_args,
645 crate fn create_substs_for_associated_item(
650 item_segment: &hir::PathSegment<'_>,
651 parent_substs: SubstsRef<'tcx>,
652 ) -> SubstsRef<'tcx> {
654 "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}",
655 span, item_def_id, item_segment
657 if tcx.generics_of(item_def_id).params.is_empty() {
658 self.prohibit_generics(slice::from_ref(item_segment));
662 self.create_substs_for_ast_path(
668 item_segment.infer_args,
675 /// Instantiates the path for the given trait reference, assuming that it's
676 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
677 /// The type _cannot_ be a type other than a trait type.
679 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
680 /// are disallowed. Otherwise, they are pushed onto the vector given.
681 pub fn instantiate_mono_trait_ref(
683 trait_ref: &hir::TraitRef<'_>,
685 ) -> ty::TraitRef<'tcx> {
686 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
688 self.ast_path_to_mono_trait_ref(
690 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
692 trait_ref.path.segments.last().unwrap(),
696 fn instantiate_poly_trait_ref_inner(
700 binding_span: Option<Span>,
701 constness: ty::BoundConstness,
702 bounds: &mut Bounds<'tcx>,
704 trait_ref_span: Span,
706 trait_segment: &hir::PathSegment<'_>,
707 args: &GenericArgs<'_>,
710 ) -> GenericArgCountResult {
711 let (substs, arg_count) = self.create_substs_for_ast_path(
721 let tcx = self.tcx();
722 let bound_vars = tcx.late_bound_vars(hir_id);
725 let assoc_bindings = self.create_assoc_bindings_for_generic_args(args);
728 ty::Binder::bind_with_vars(ty::TraitRef::new(trait_def_id, substs), bound_vars);
730 debug!(?poly_trait_ref, ?assoc_bindings);
731 bounds.trait_bounds.push((poly_trait_ref, span, constness));
733 let mut dup_bindings = FxHashMap::default();
734 for binding in &assoc_bindings {
735 // Specify type to assert that error was already reported in `Err` case.
736 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
743 binding_span.unwrap_or(binding.span),
745 // Okay to ignore `Err` because of `ErrorReported` (see above).
751 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
752 /// a full trait reference. The resulting trait reference is returned. This may also generate
753 /// auxiliary bounds, which are added to `bounds`.
758 /// poly_trait_ref = Iterator<Item = u32>
762 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
764 /// **A note on binders:** against our usual convention, there is an implied bounder around
765 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
766 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
767 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
768 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
770 #[tracing::instrument(level = "debug", skip(self, span, constness, bounds, speculative))]
771 pub(crate) fn instantiate_poly_trait_ref(
773 trait_ref: &hir::TraitRef<'_>,
775 constness: ty::BoundConstness,
777 bounds: &mut Bounds<'tcx>,
779 ) -> GenericArgCountResult {
780 let hir_id = trait_ref.hir_ref_id;
781 let binding_span = None;
782 let trait_ref_span = trait_ref.path.span;
783 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
784 let trait_segment = trait_ref.path.segments.last().unwrap();
785 let args = trait_segment.args();
786 let infer_args = trait_segment.infer_args;
788 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
789 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
791 self.instantiate_poly_trait_ref_inner(
807 pub(crate) fn instantiate_lang_item_trait_ref(
809 lang_item: hir::LangItem,
812 args: &GenericArgs<'_>,
814 bounds: &mut Bounds<'tcx>,
816 let binding_span = Some(span);
817 let constness = ty::BoundConstness::NotConst;
818 let speculative = false;
819 let trait_ref_span = span;
820 let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
821 let trait_segment = &hir::PathSegment::invalid();
822 let infer_args = false;
824 self.instantiate_poly_trait_ref_inner(
840 fn ast_path_to_mono_trait_ref(
845 trait_segment: &hir::PathSegment<'_>,
846 ) -> ty::TraitRef<'tcx> {
848 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
849 let assoc_bindings = self.create_assoc_bindings_for_generic_args(trait_segment.args());
850 if let Some(b) = assoc_bindings.first() {
851 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
853 ty::TraitRef::new(trait_def_id, substs)
856 #[tracing::instrument(level = "debug", skip(self, span))]
857 fn create_substs_for_ast_trait_ref<'a>(
862 trait_segment: &'a hir::PathSegment<'a>,
863 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
864 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
866 self.create_substs_for_ast_path(
871 trait_segment.args(),
872 trait_segment.infer_args,
877 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
879 .associated_items(trait_def_id)
880 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
884 // Sets `implicitly_sized` to true on `Bounds` if necessary
885 pub(crate) fn add_implicitly_sized<'hir>(
887 bounds: &mut Bounds<'hir>,
888 ast_bounds: &'hir [hir::GenericBound<'hir>],
889 self_ty_where_predicates: Option<(hir::HirId, &'hir [hir::WherePredicate<'hir>])>,
892 let tcx = self.tcx();
894 // Try to find an unbound in bounds.
895 let mut unbound = None;
896 let mut search_bounds = |ast_bounds: &'hir [hir::GenericBound<'hir>]| {
897 for ab in ast_bounds {
898 if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab {
899 if unbound.is_none() {
900 unbound = Some(&ptr.trait_ref);
902 tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span });
907 search_bounds(ast_bounds);
908 if let Some((self_ty, where_clause)) = self_ty_where_predicates {
909 let self_ty_def_id = tcx.hir().local_def_id(self_ty).to_def_id();
910 for clause in where_clause {
912 hir::WherePredicate::BoundPredicate(pred) => {
913 match pred.bounded_ty.kind {
914 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => match path.res {
915 Res::Def(DefKind::TyParam, def_id) if def_id == self_ty_def_id => {}
920 search_bounds(pred.bounds);
927 let sized_def_id = tcx.lang_items().require(LangItem::Sized);
928 match (&sized_def_id, unbound) {
929 (Ok(sized_def_id), Some(tpb))
930 if tpb.path.res == Res::Def(DefKind::Trait, *sized_def_id) =>
932 // There was in fact a `?Sized` bound, return without doing anything
936 // There was a `?Trait` bound, but it was not `?Sized`; warn.
939 "default bound relaxed for a type parameter, but \
940 this does nothing because the given bound is not \
941 a default; only `?Sized` is supported",
943 // Otherwise, add implicitly sized if `Sized` is available.
946 // There was no `?Sized` bound; add implicitly sized if `Sized` is available.
949 if sized_def_id.is_err() {
950 // No lang item for `Sized`, so we can't add it as a bound.
953 bounds.implicitly_sized = Some(span);
956 /// This helper takes a *converted* parameter type (`param_ty`)
957 /// and an *unconverted* list of bounds:
961 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
963 /// `param_ty`, in ty form
966 /// It adds these `ast_bounds` into the `bounds` structure.
968 /// **A note on binders:** there is an implied binder around
969 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
970 /// for more details.
971 #[tracing::instrument(level = "debug", skip(self, ast_bounds, bounds))]
972 pub(crate) fn add_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'hir>>>(
976 bounds: &mut Bounds<'tcx>,
977 bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
979 for ast_bound in ast_bounds {
981 hir::GenericBound::Trait(poly_trait_ref, modifier) => {
982 let constness = match modifier {
983 hir::TraitBoundModifier::MaybeConst => ty::BoundConstness::ConstIfConst,
984 hir::TraitBoundModifier::None => ty::BoundConstness::NotConst,
985 hir::TraitBoundModifier::Maybe => continue,
988 let _ = self.instantiate_poly_trait_ref(
989 &poly_trait_ref.trait_ref,
997 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
998 self.instantiate_lang_item_trait_ref(
999 lang_item, span, hir_id, args, param_ty, bounds,
1002 hir::GenericBound::Outlives(lifetime) => {
1003 let region = self.ast_region_to_region(lifetime, None);
1006 .push((ty::Binder::bind_with_vars(region, bound_vars), lifetime.span));
1012 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1013 /// The self-type for the bounds is given by `param_ty`.
1018 /// fn foo<T: Bar + Baz>() { }
1019 /// ^ ^^^^^^^^^ ast_bounds
1023 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1024 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1025 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1027 /// `span` should be the declaration size of the parameter.
1028 pub(crate) fn compute_bounds(
1031 ast_bounds: &[hir::GenericBound<'_>],
1033 self.compute_bounds_inner(param_ty, &ast_bounds)
1036 /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type
1037 /// named `assoc_name` into ty::Bounds. Ignore the rest.
1038 pub(crate) fn compute_bounds_that_match_assoc_type(
1041 ast_bounds: &[hir::GenericBound<'_>],
1044 let mut result = Vec::new();
1046 for ast_bound in ast_bounds {
1047 if let Some(trait_ref) = ast_bound.trait_ref() {
1048 if let Some(trait_did) = trait_ref.trait_def_id() {
1049 if self.tcx().trait_may_define_assoc_type(trait_did, assoc_name) {
1050 result.push(ast_bound.clone());
1056 self.compute_bounds_inner(param_ty, &result)
1059 fn compute_bounds_inner(
1062 ast_bounds: &[hir::GenericBound<'_>],
1064 let mut bounds = Bounds::default();
1066 self.add_bounds(param_ty, ast_bounds.iter(), &mut bounds, ty::List::empty());
1071 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1074 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1075 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1076 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1077 #[tracing::instrument(
1079 skip(self, bounds, speculative, dup_bindings, path_span)
1081 fn add_predicates_for_ast_type_binding(
1083 hir_ref_id: hir::HirId,
1084 trait_ref: ty::PolyTraitRef<'tcx>,
1085 binding: &ConvertedBinding<'_, 'tcx>,
1086 bounds: &mut Bounds<'tcx>,
1088 dup_bindings: &mut FxHashMap<DefId, Span>,
1090 ) -> Result<(), ErrorReported> {
1091 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1092 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1093 // subtle in the event that `T` is defined in a supertrait of
1094 // `SomeTrait`, because in that case we need to upcast.
1096 // That is, consider this case:
1099 // trait SubTrait: SuperTrait<i32> { }
1100 // trait SuperTrait<A> { type T; }
1102 // ... B: SubTrait<T = foo> ...
1105 // We want to produce `<B as SuperTrait<i32>>::T == foo`.
1107 let tcx = self.tcx();
1110 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1111 // Simple case: X is defined in the current trait.
1114 // Otherwise, we have to walk through the supertraits to find
1116 self.one_bound_for_assoc_type(
1117 || traits::supertraits(tcx, trait_ref),
1118 || trait_ref.print_only_trait_path().to_string(),
1121 || match binding.kind {
1122 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1128 let (assoc_ident, def_scope) =
1129 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1131 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1132 // of calling `filter_by_name_and_kind`.
1134 .associated_items(candidate.def_id())
1135 .filter_by_name_unhygienic(assoc_ident.name)
1137 i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident
1139 .expect("missing associated type");
1141 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1145 &format!("associated type `{}` is private", binding.item_name),
1147 .span_label(binding.span, "private associated type")
1150 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span, None);
1154 .entry(assoc_ty.def_id)
1155 .and_modify(|prev_span| {
1156 self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified {
1158 prev_span: *prev_span,
1159 item_name: binding.item_name,
1160 def_path: tcx.def_path_str(assoc_ty.container.id()),
1163 .or_insert(binding.span);
1166 // Include substitutions for generic parameters of associated types
1167 let projection_ty = candidate.map_bound(|trait_ref| {
1168 let ident = Ident::new(assoc_ty.ident.name, binding.item_name.span);
1169 let item_segment = hir::PathSegment {
1171 hir_id: Some(binding.hir_id),
1173 args: Some(binding.gen_args),
1177 let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item(
1186 "add_predicates_for_ast_type_binding: substs for trait-ref and assoc_item: {:?}",
1187 substs_trait_ref_and_assoc_item
1191 item_def_id: assoc_ty.def_id,
1192 substs: substs_trait_ref_and_assoc_item,
1197 // Find any late-bound regions declared in `ty` that are not
1198 // declared in the trait-ref or assoc_ty. These are not well-formed.
1202 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1203 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1204 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1205 let late_bound_in_trait_ref =
1206 tcx.collect_constrained_late_bound_regions(&projection_ty);
1207 let late_bound_in_ty =
1208 tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty));
1209 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1210 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1212 // FIXME: point at the type params that don't have appropriate lifetimes:
1213 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1214 // ---- ---- ^^^^^^^
1215 self.validate_late_bound_regions(
1216 late_bound_in_trait_ref,
1223 "binding for associated type `{}` references {}, \
1224 which does not appear in the trait input types",
1233 match binding.kind {
1234 ConvertedBindingKind::Equality(ref ty) => {
1235 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1236 // the "projection predicate" for:
1238 // `<T as Iterator>::Item = u32`
1239 bounds.projection_bounds.push((
1240 projection_ty.map_bound(|projection_ty| {
1242 "add_predicates_for_ast_type_binding: projection_ty {:?}, substs: {:?}",
1243 projection_ty, projection_ty.substs
1245 ty::ProjectionPredicate { projection_ty, ty }
1250 ConvertedBindingKind::Constraint(ast_bounds) => {
1251 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1253 // `<T as Iterator>::Item: Debug`
1255 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1256 // parameter to have a skipped binder.
1257 let param_ty = tcx.mk_ty(ty::Projection(projection_ty.skip_binder()));
1258 self.add_bounds(param_ty, ast_bounds.iter(), bounds, candidate.bound_vars());
1268 item_segment: &hir::PathSegment<'_>,
1270 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1271 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1274 fn conv_object_ty_poly_trait_ref(
1277 trait_bounds: &[hir::PolyTraitRef<'_>],
1278 lifetime: &hir::Lifetime,
1281 let tcx = self.tcx();
1283 let mut bounds = Bounds::default();
1284 let mut potential_assoc_types = Vec::new();
1285 let dummy_self = self.tcx().types.trait_object_dummy_self;
1286 for trait_bound in trait_bounds.iter().rev() {
1287 if let GenericArgCountResult {
1289 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1291 } = self.instantiate_poly_trait_ref(
1292 &trait_bound.trait_ref,
1294 ty::BoundConstness::NotConst,
1299 potential_assoc_types.extend(cur_potential_assoc_types);
1303 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1304 // is used and no 'maybe' bounds are used.
1305 let expanded_traits =
1306 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1307 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1308 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1309 if regular_traits.len() > 1 {
1310 let first_trait = ®ular_traits[0];
1311 let additional_trait = ®ular_traits[1];
1312 let mut err = struct_span_err!(
1314 additional_trait.bottom().1,
1316 "only auto traits can be used as additional traits in a trait object"
1318 additional_trait.label_with_exp_info(
1320 "additional non-auto trait",
1323 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1325 "consider creating a new trait with all of these as super-traits and using that \
1326 trait here instead: `trait NewTrait: {} {{}}`",
1329 .map(|t| t.trait_ref().print_only_trait_path().to_string())
1330 .collect::<Vec<_>>()
1334 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1335 for more information on them, visit \
1336 <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1341 if regular_traits.is_empty() && auto_traits.is_empty() {
1342 tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span });
1343 return tcx.ty_error();
1346 // Check that there are no gross object safety violations;
1347 // most importantly, that the supertraits don't contain `Self`,
1349 for item in ®ular_traits {
1350 let object_safety_violations =
1351 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1352 if !object_safety_violations.is_empty() {
1353 report_object_safety_error(
1356 item.trait_ref().def_id(),
1357 &object_safety_violations[..],
1360 return tcx.ty_error();
1364 // Use a `BTreeSet` to keep output in a more consistent order.
1365 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1367 let regular_traits_refs_spans = bounds
1370 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1372 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1373 assert_eq!(constness, ty::BoundConstness::NotConst);
1375 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1377 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1378 obligation.predicate
1381 let bound_predicate = obligation.predicate.kind();
1382 match bound_predicate.skip_binder() {
1383 ty::PredicateKind::Trait(pred) => {
1384 let pred = bound_predicate.rebind(pred);
1385 associated_types.entry(span).or_default().extend(
1386 tcx.associated_items(pred.def_id())
1387 .in_definition_order()
1388 .filter(|item| item.kind == ty::AssocKind::Type)
1389 .map(|item| item.def_id),
1392 ty::PredicateKind::Projection(pred) => {
1393 let pred = bound_predicate.rebind(pred);
1394 // A `Self` within the original bound will be substituted with a
1395 // `trait_object_dummy_self`, so check for that.
1396 let references_self =
1397 pred.skip_binder().ty.walk(tcx).any(|arg| arg == dummy_self.into());
1399 // If the projection output contains `Self`, force the user to
1400 // elaborate it explicitly to avoid a lot of complexity.
1402 // The "classicaly useful" case is the following:
1404 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1409 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1410 // but actually supporting that would "expand" to an infinitely-long type
1411 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1413 // Instead, we force the user to write
1414 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1415 // the discussion in #56288 for alternatives.
1416 if !references_self {
1417 // Include projections defined on supertraits.
1418 bounds.projection_bounds.push((pred, span));
1426 for (projection_bound, _) in &bounds.projection_bounds {
1427 for def_ids in associated_types.values_mut() {
1428 def_ids.remove(&projection_bound.projection_def_id());
1432 self.complain_about_missing_associated_types(
1434 potential_assoc_types,
1438 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1439 // `dyn Trait + Send`.
1440 // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering
1442 let mut duplicates = FxHashSet::default();
1443 auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id()));
1444 debug!("regular_traits: {:?}", regular_traits);
1445 debug!("auto_traits: {:?}", auto_traits);
1447 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1448 let existential_trait_refs = regular_traits.iter().map(|i| {
1449 i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| {
1450 if trait_ref.self_ty() != dummy_self {
1451 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1452 // which picks up non-supertraits where clauses - but also, the object safety
1453 // completely ignores trait aliases, which could be object safety hazards. We
1454 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1455 // disabled. (#66420)
1456 tcx.sess.delay_span_bug(
1459 "trait_ref_to_existential called on {:?} with non-dummy Self",
1464 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1467 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1468 bound.map_bound(|b| {
1469 if b.projection_ty.self_ty() != dummy_self {
1470 tcx.sess.delay_span_bug(
1472 &format!("trait_ref_to_existential called on {:?} with non-dummy Self", b),
1475 ty::ExistentialProjection::erase_self_ty(tcx, b)
1479 let regular_trait_predicates = existential_trait_refs
1480 .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait));
1481 let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| {
1482 ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()))
1484 // N.b. principal, projections, auto traits
1485 // FIXME: This is actually wrong with multiple principals in regards to symbol mangling
1486 let mut v = regular_trait_predicates
1488 existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)),
1490 .chain(auto_trait_predicates)
1491 .collect::<SmallVec<[_; 8]>>();
1492 v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
1494 let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter());
1496 // Use explicitly-specified region bound.
1497 let region_bound = if !lifetime.is_elided() {
1498 self.ast_region_to_region(lifetime, None)
1500 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1501 if tcx.named_region(lifetime.hir_id).is_some() {
1502 self.ast_region_to_region(lifetime, None)
1504 self.re_infer(None, span).unwrap_or_else(|| {
1505 let mut err = struct_span_err!(
1509 "the lifetime bound for this object type cannot be deduced \
1510 from context; please supply an explicit bound"
1513 // We will have already emitted an error E0106 complaining about a
1514 // missing named lifetime in `&dyn Trait`, so we elide this one.
1519 tcx.lifetimes.re_static
1524 debug!("region_bound: {:?}", region_bound);
1526 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1527 debug!("trait_object_type: {:?}", ty);
1531 fn report_ambiguous_associated_type(
1538 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1539 if let (true, Ok(snippet)) = (
1542 .confused_type_with_std_module
1544 .any(|full_span| full_span.contains(span)),
1545 self.tcx().sess.source_map().span_to_snippet(span),
1547 err.span_suggestion(
1549 "you are looking for the module in `std`, not the primitive type",
1550 format!("std::{}", snippet),
1551 Applicability::MachineApplicable,
1554 err.span_suggestion(
1556 "use fully-qualified syntax",
1557 format!("<{} as {}>::{}", type_str, trait_str, name),
1558 Applicability::HasPlaceholders,
1564 // Search for a bound on a type parameter which includes the associated item
1565 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1566 // This function will fail if there are no suitable bounds or there is
1568 fn find_bound_for_assoc_item(
1570 ty_param_def_id: LocalDefId,
1573 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
1574 let tcx = self.tcx();
1577 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1578 ty_param_def_id, assoc_name, span,
1581 let predicates = &self
1582 .get_type_parameter_bounds(span, ty_param_def_id.to_def_id(), assoc_name)
1585 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1587 let param_hir_id = tcx.hir().local_def_id_to_hir_id(ty_param_def_id);
1588 let param_name = tcx.hir().ty_param_name(param_hir_id);
1589 self.one_bound_for_assoc_type(
1591 traits::transitive_bounds_that_define_assoc_type(
1593 predicates.iter().filter_map(|(p, _)| {
1594 p.to_opt_poly_trait_ref().map(|trait_ref| trait_ref.value)
1599 || param_name.to_string(),
1606 // Checks that `bounds` contains exactly one element and reports appropriate
1607 // errors otherwise.
1608 fn one_bound_for_assoc_type<I>(
1610 all_candidates: impl Fn() -> I,
1611 ty_param_name: impl Fn() -> String,
1614 is_equality: impl Fn() -> Option<String>,
1615 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1617 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1619 let mut matching_candidates = all_candidates()
1620 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1622 let bound = match matching_candidates.next() {
1623 Some(bound) => bound,
1625 self.complain_about_assoc_type_not_found(
1631 return Err(ErrorReported);
1635 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1637 if let Some(bound2) = matching_candidates.next() {
1638 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1640 let is_equality = is_equality();
1641 let bounds = array::IntoIter::new([bound, bound2]).chain(matching_candidates);
1642 let mut err = if is_equality.is_some() {
1643 // More specific Error Index entry.
1648 "ambiguous associated type `{}` in bounds of `{}`",
1657 "ambiguous associated type `{}` in bounds of `{}`",
1662 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1664 let mut where_bounds = vec![];
1665 for bound in bounds {
1666 let bound_id = bound.def_id();
1667 let bound_span = self
1669 .associated_items(bound_id)
1670 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
1671 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1673 if let Some(bound_span) = bound_span {
1677 "ambiguous `{}` from `{}`",
1679 bound.print_only_trait_path(),
1682 if let Some(constraint) = &is_equality {
1683 where_bounds.push(format!(
1684 " T: {trait}::{assoc} = {constraint}",
1685 trait=bound.print_only_trait_path(),
1687 constraint=constraint,
1690 err.span_suggestion_verbose(
1691 span.with_hi(assoc_name.span.lo()),
1692 "use fully qualified syntax to disambiguate",
1696 bound.print_only_trait_path(),
1698 Applicability::MaybeIncorrect,
1703 "associated type `{}` could derive from `{}`",
1705 bound.print_only_trait_path(),
1709 if !where_bounds.is_empty() {
1711 "consider introducing a new type parameter `T` and adding `where` constraints:\
1712 \n where\n T: {},\n{}",
1714 where_bounds.join(",\n"),
1718 if !where_bounds.is_empty() {
1719 return Err(ErrorReported);
1725 // Create a type from a path to an associated type.
1726 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1727 // and item_segment is the path segment for `D`. We return a type and a def for
1729 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1730 // parameter or `Self`.
1731 // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1732 // it should also start reportint the `BARE_TRAIT_OBJECTS` lint.
1733 pub fn associated_path_to_ty(
1735 hir_ref_id: hir::HirId,
1739 assoc_segment: &hir::PathSegment<'_>,
1740 permit_variants: bool,
1741 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
1742 let tcx = self.tcx();
1743 let assoc_ident = assoc_segment.ident;
1745 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1747 // Check if we have an enum variant.
1748 let mut variant_resolution = None;
1749 if let ty::Adt(adt_def, _) = qself_ty.kind() {
1750 if adt_def.is_enum() {
1751 let variant_def = adt_def
1754 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
1755 if let Some(variant_def) = variant_def {
1756 if permit_variants {
1757 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None);
1758 self.prohibit_generics(slice::from_ref(assoc_segment));
1759 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1761 variant_resolution = Some(variant_def.def_id);
1767 // Find the type of the associated item, and the trait where the associated
1768 // item is declared.
1769 let bound = match (&qself_ty.kind(), qself_res) {
1770 (_, Res::SelfTy(Some(_), Some((impl_def_id, _)))) => {
1771 // `Self` in an impl of a trait -- we have a concrete self type and a
1773 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1774 Some(trait_ref) => trait_ref,
1776 // A cycle error occurred, most likely.
1777 return Err(ErrorReported);
1781 self.one_bound_for_assoc_type(
1782 || traits::supertraits(tcx, ty::Binder::dummy(trait_ref)),
1783 || "Self".to_string(),
1791 Res::SelfTy(Some(param_did), None) | Res::Def(DefKind::TyParam, param_did),
1792 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
1794 if variant_resolution.is_some() {
1795 // Variant in type position
1796 let msg = format!("expected type, found variant `{}`", assoc_ident);
1797 tcx.sess.span_err(span, &msg);
1798 } else if qself_ty.is_enum() {
1799 let mut err = struct_span_err!(
1803 "no variant named `{}` found for enum `{}`",
1808 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1809 if let Some(suggested_name) = find_best_match_for_name(
1813 .map(|variant| variant.ident.name)
1814 .collect::<Vec<Symbol>>(),
1818 err.span_suggestion(
1820 "there is a variant with a similar name",
1821 suggested_name.to_string(),
1822 Applicability::MaybeIncorrect,
1827 format!("variant not found in `{}`", qself_ty),
1831 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
1832 let sp = tcx.sess.source_map().guess_head_span(sp);
1833 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1837 } else if !qself_ty.references_error() {
1838 // Don't print `TyErr` to the user.
1839 self.report_ambiguous_associated_type(
1841 &qself_ty.to_string(),
1846 return Err(ErrorReported);
1850 let trait_did = bound.def_id();
1851 let (assoc_ident, def_scope) =
1852 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1854 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1855 // of calling `filter_by_name_and_kind`.
1857 .associated_items(trait_did)
1858 .in_definition_order()
1860 i.kind.namespace() == Namespace::TypeNS
1861 && i.ident.normalize_to_macros_2_0() == assoc_ident
1863 .expect("missing associated type");
1865 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
1866 let ty = self.normalize_ty(span, ty);
1868 let kind = DefKind::AssocTy;
1869 if !item.vis.is_accessible_from(def_scope, tcx) {
1870 let kind = kind.descr(item.def_id);
1871 let msg = format!("{} `{}` is private", kind, assoc_ident);
1873 .struct_span_err(span, &msg)
1874 .span_label(span, &format!("private {}", kind))
1877 tcx.check_stability(item.def_id, Some(hir_ref_id), span, None);
1879 if let Some(variant_def_id) = variant_resolution {
1880 tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
1881 let mut err = lint.build("ambiguous associated item");
1882 let mut could_refer_to = |kind: DefKind, def_id, also| {
1883 let note_msg = format!(
1884 "`{}` could{} refer to the {} defined here",
1889 err.span_note(tcx.def_span(def_id), ¬e_msg);
1892 could_refer_to(DefKind::Variant, variant_def_id, "");
1893 could_refer_to(kind, item.def_id, " also");
1895 err.span_suggestion(
1897 "use fully-qualified syntax",
1898 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
1899 Applicability::MachineApplicable,
1905 Ok((ty, kind, item.def_id))
1911 opt_self_ty: Option<Ty<'tcx>>,
1913 trait_segment: &hir::PathSegment<'_>,
1914 item_segment: &hir::PathSegment<'_>,
1916 let tcx = self.tcx();
1918 let trait_def_id = tcx.parent(item_def_id).unwrap();
1920 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
1922 let self_ty = if let Some(ty) = opt_self_ty {
1925 let path_str = tcx.def_path_str(trait_def_id);
1927 let def_id = self.item_def_id();
1929 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
1931 let parent_def_id = def_id
1932 .and_then(|def_id| {
1933 def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
1935 .map(|hir_id| tcx.hir().get_parent_did(hir_id).to_def_id());
1937 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
1939 // If the trait in segment is the same as the trait defining the item,
1940 // use the `<Self as ..>` syntax in the error.
1941 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
1942 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
1944 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
1950 self.report_ambiguous_associated_type(
1954 item_segment.ident.name,
1956 return tcx.ty_error();
1959 debug!("qpath_to_ty: self_type={:?}", self_ty);
1961 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
1963 let item_substs = self.create_substs_for_associated_item(
1971 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1973 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
1976 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
1980 let mut has_err = false;
1981 for segment in segments {
1982 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
1983 for arg in segment.args().args {
1984 let (span, kind) = match arg {
1985 hir::GenericArg::Lifetime(lt) => {
1991 (lt.span, "lifetime")
1993 hir::GenericArg::Type(ty) => {
2001 hir::GenericArg::Const(ct) => {
2009 hir::GenericArg::Infer(inf) => {
2015 (inf.span, "generic")
2018 let mut err = struct_span_err!(
2022 "{} arguments are not allowed for this type",
2025 err.span_label(span, format!("{} argument not allowed", kind));
2027 if err_for_lt && err_for_ty && err_for_ct {
2032 // Only emit the first error to avoid overloading the user with error messages.
2033 if let [binding, ..] = segment.args().bindings {
2035 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2041 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2042 pub fn def_ids_for_value_path_segments(
2044 segments: &[hir::PathSegment<'_>],
2045 self_ty: Option<Ty<'tcx>>,
2049 // We need to extract the type parameters supplied by the user in
2050 // the path `path`. Due to the current setup, this is a bit of a
2051 // tricky-process; the problem is that resolve only tells us the
2052 // end-point of the path resolution, and not the intermediate steps.
2053 // Luckily, we can (at least for now) deduce the intermediate steps
2054 // just from the end-point.
2056 // There are basically five cases to consider:
2058 // 1. Reference to a constructor of a struct:
2060 // struct Foo<T>(...)
2062 // In this case, the parameters are declared in the type space.
2064 // 2. Reference to a constructor of an enum variant:
2066 // enum E<T> { Foo(...) }
2068 // In this case, the parameters are defined in the type space,
2069 // but may be specified either on the type or the variant.
2071 // 3. Reference to a fn item or a free constant:
2075 // In this case, the path will again always have the form
2076 // `a::b::foo::<T>` where only the final segment should have
2077 // type parameters. However, in this case, those parameters are
2078 // declared on a value, and hence are in the `FnSpace`.
2080 // 4. Reference to a method or an associated constant:
2082 // impl<A> SomeStruct<A> {
2086 // Here we can have a path like
2087 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2088 // may appear in two places. The penultimate segment,
2089 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2090 // final segment, `foo::<B>` contains parameters in fn space.
2092 // The first step then is to categorize the segments appropriately.
2094 let tcx = self.tcx();
2096 assert!(!segments.is_empty());
2097 let last = segments.len() - 1;
2099 let mut path_segs = vec![];
2102 // Case 1. Reference to a struct constructor.
2103 DefKind::Ctor(CtorOf::Struct, ..) => {
2104 // Everything but the final segment should have no
2105 // parameters at all.
2106 let generics = tcx.generics_of(def_id);
2107 // Variant and struct constructors use the
2108 // generics of their parent type definition.
2109 let generics_def_id = generics.parent.unwrap_or(def_id);
2110 path_segs.push(PathSeg(generics_def_id, last));
2113 // Case 2. Reference to a variant constructor.
2114 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2115 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2116 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2117 debug_assert!(adt_def.is_enum());
2119 } else if last >= 1 && segments[last - 1].args.is_some() {
2120 // Everything but the penultimate segment should have no
2121 // parameters at all.
2122 let mut def_id = def_id;
2124 // `DefKind::Ctor` -> `DefKind::Variant`
2125 if let DefKind::Ctor(..) = kind {
2126 def_id = tcx.parent(def_id).unwrap()
2129 // `DefKind::Variant` -> `DefKind::Enum`
2130 let enum_def_id = tcx.parent(def_id).unwrap();
2131 (enum_def_id, last - 1)
2133 // FIXME: lint here recommending `Enum::<...>::Variant` form
2134 // instead of `Enum::Variant::<...>` form.
2136 // Everything but the final segment should have no
2137 // parameters at all.
2138 let generics = tcx.generics_of(def_id);
2139 // Variant and struct constructors use the
2140 // generics of their parent type definition.
2141 (generics.parent.unwrap_or(def_id), last)
2143 path_segs.push(PathSeg(generics_def_id, index));
2146 // Case 3. Reference to a top-level value.
2147 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2148 path_segs.push(PathSeg(def_id, last));
2151 // Case 4. Reference to a method or associated const.
2152 DefKind::AssocFn | DefKind::AssocConst => {
2153 if segments.len() >= 2 {
2154 let generics = tcx.generics_of(def_id);
2155 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2157 path_segs.push(PathSeg(def_id, last));
2160 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2163 debug!("path_segs = {:?}", path_segs);
2168 // Check a type `Path` and convert it to a `Ty`.
2171 opt_self_ty: Option<Ty<'tcx>>,
2172 path: &hir::Path<'_>,
2173 permit_variants: bool,
2175 let tcx = self.tcx();
2178 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2179 path.res, opt_self_ty, path.segments
2182 let span = path.span;
2184 Res::Def(DefKind::OpaqueTy, did) => {
2185 // Check for desugared `impl Trait`.
2186 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2187 let item_segment = path.segments.split_last().unwrap();
2188 self.prohibit_generics(item_segment.1);
2189 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2190 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2197 | DefKind::ForeignTy,
2200 assert_eq!(opt_self_ty, None);
2201 self.prohibit_generics(path.segments.split_last().unwrap().1);
2202 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2204 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2205 // Convert "variant type" as if it were a real type.
2206 // The resulting `Ty` is type of the variant's enum for now.
2207 assert_eq!(opt_self_ty, None);
2210 self.def_ids_for_value_path_segments(&path.segments, None, kind, def_id);
2211 let generic_segs: FxHashSet<_> =
2212 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2213 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2215 if !generic_segs.contains(&index) { Some(seg) } else { None }
2219 let PathSeg(def_id, index) = path_segs.last().unwrap();
2220 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2222 Res::Def(DefKind::TyParam, def_id) => {
2223 assert_eq!(opt_self_ty, None);
2224 self.prohibit_generics(path.segments);
2226 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
2227 let item_id = tcx.hir().get_parent_node(hir_id);
2228 let item_def_id = tcx.hir().local_def_id(item_id);
2229 let generics = tcx.generics_of(item_def_id);
2230 let index = generics.param_def_id_to_index[&def_id];
2231 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2233 Res::SelfTy(Some(_), None) => {
2234 // `Self` in trait or type alias.
2235 assert_eq!(opt_self_ty, None);
2236 self.prohibit_generics(path.segments);
2237 tcx.types.self_param
2239 Res::SelfTy(_, Some((def_id, forbid_generic))) => {
2240 // `Self` in impl (we know the concrete type).
2241 assert_eq!(opt_self_ty, None);
2242 self.prohibit_generics(path.segments);
2243 // Try to evaluate any array length constants.
2244 let normalized_ty = self.normalize_ty(span, tcx.at(span).type_of(def_id));
2245 if forbid_generic && normalized_ty.definitely_needs_subst(tcx) {
2246 let mut err = tcx.sess.struct_span_err(
2248 "generic `Self` types are currently not permitted in anonymous constants",
2250 if let Some(hir::Node::Item(&hir::Item {
2251 kind: hir::ItemKind::Impl(ref impl_),
2253 })) = tcx.hir().get_if_local(def_id)
2255 err.span_note(impl_.self_ty.span, "not a concrete type");
2263 Res::Def(DefKind::AssocTy, def_id) => {
2264 debug_assert!(path.segments.len() >= 2);
2265 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2270 &path.segments[path.segments.len() - 2],
2271 path.segments.last().unwrap(),
2274 Res::PrimTy(prim_ty) => {
2275 assert_eq!(opt_self_ty, None);
2276 self.prohibit_generics(path.segments);
2278 hir::PrimTy::Bool => tcx.types.bool,
2279 hir::PrimTy::Char => tcx.types.char,
2280 hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2281 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2282 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2283 hir::PrimTy::Str => tcx.types.str_,
2287 self.set_tainted_by_errors();
2288 self.tcx().ty_error()
2290 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2294 /// Parses the programmer's textual representation of a type into our
2295 /// internal notion of a type.
2296 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2297 self.ast_ty_to_ty_inner(ast_ty, false)
2300 /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2301 /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2302 #[tracing::instrument(level = "debug", skip(self))]
2303 fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool) -> Ty<'tcx> {
2304 let tcx = self.tcx();
2306 let result_ty = match ast_ty.kind {
2307 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(&ty)),
2308 hir::TyKind::Ptr(ref mt) => {
2309 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(&mt.ty), mutbl: mt.mutbl })
2311 hir::TyKind::Rptr(ref region, ref mt) => {
2312 let r = self.ast_region_to_region(region, None);
2314 let t = self.ast_ty_to_ty_inner(&mt.ty, true);
2315 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2317 hir::TyKind::Never => tcx.types.never,
2318 hir::TyKind::Tup(ref fields) => {
2319 tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(&t)))
2321 hir::TyKind::BareFn(ref bf) => {
2322 require_c_abi_if_c_variadic(tcx, &bf.decl, bf.abi, ast_ty.span);
2324 tcx.mk_fn_ptr(self.ty_of_fn(
2329 &hir::Generics::empty(),
2334 hir::TyKind::TraitObject(ref bounds, ref lifetime, _) => {
2335 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed)
2337 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2338 debug!(?maybe_qself, ?path);
2339 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2340 self.res_to_ty(opt_self_ty, path, false)
2342 hir::TyKind::OpaqueDef(item_id, ref lifetimes) => {
2343 let opaque_ty = tcx.hir().item(item_id);
2344 let def_id = item_id.def_id.to_def_id();
2346 match opaque_ty.kind {
2347 hir::ItemKind::OpaqueTy(hir::OpaqueTy { impl_trait_fn, .. }) => {
2348 self.impl_trait_ty_to_ty(def_id, lifetimes, impl_trait_fn.is_some())
2350 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2353 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2354 debug!(?qself, ?segment);
2355 let ty = self.ast_ty_to_ty(qself);
2357 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
2362 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2363 .map(|(ty, _, _)| ty)
2364 .unwrap_or_else(|_| tcx.ty_error())
2366 hir::TyKind::Path(hir::QPath::LangItem(lang_item, span)) => {
2367 let def_id = tcx.require_lang_item(lang_item, Some(span));
2368 let (substs, _) = self.create_substs_for_ast_path(
2372 &hir::PathSegment::invalid(),
2373 &GenericArgs::none(),
2377 self.normalize_ty(span, tcx.at(span).type_of(def_id).subst(tcx, substs))
2379 hir::TyKind::Array(ref ty, ref length) => {
2380 let length_def_id = tcx.hir().local_def_id(length.hir_id);
2381 let length = ty::Const::from_anon_const(tcx, length_def_id);
2382 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(&ty), length));
2383 self.normalize_ty(ast_ty.span, array_ty)
2385 hir::TyKind::Typeof(ref e) => {
2386 tcx.sess.emit_err(TypeofReservedKeywordUsed { span: ast_ty.span });
2387 tcx.type_of(tcx.hir().local_def_id(e.hir_id))
2389 hir::TyKind::Infer => {
2390 // Infer also appears as the type of arguments or return
2391 // values in an ExprKind::Closure, or as
2392 // the type of local variables. Both of these cases are
2393 // handled specially and will not descend into this routine.
2394 self.ty_infer(None, ast_ty.span)
2396 hir::TyKind::Err => tcx.ty_error(),
2401 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2405 fn impl_trait_ty_to_ty(
2408 lifetimes: &[hir::GenericArg<'_>],
2409 replace_parent_lifetimes: bool,
2411 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2412 let tcx = self.tcx();
2414 let generics = tcx.generics_of(def_id);
2416 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2417 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2418 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2419 // Our own parameters are the resolved lifetimes.
2421 GenericParamDefKind::Lifetime
2422 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] =>
2424 self.ast_region_to_region(lifetime, None).into()
2430 // For RPIT (return position impl trait), only lifetimes
2431 // mentioned in the impl Trait predicate are captured by
2432 // the opaque type, so the lifetime parameters from the
2433 // parent item need to be replaced with `'static`.
2435 // For `impl Trait` in the types of statics, constants,
2436 // locals and type aliases. These capture all parent
2437 // lifetimes, so they can use their identity subst.
2438 GenericParamDefKind::Lifetime if replace_parent_lifetimes => {
2439 tcx.lifetimes.re_static.into()
2441 _ => tcx.mk_param_from_def(param),
2445 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2447 let ty = tcx.mk_opaque(def_id, substs);
2448 debug!("impl_trait_ty_to_ty: {}", ty);
2452 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2454 hir::TyKind::Infer if expected_ty.is_some() => {
2455 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2456 expected_ty.unwrap()
2458 _ => self.ast_ty_to_ty(ty),
2465 unsafety: hir::Unsafety,
2467 decl: &hir::FnDecl<'_>,
2468 generics: &hir::Generics<'_>,
2469 ident_span: Option<Span>,
2470 hir_ty: Option<&hir::Ty<'_>>,
2471 ) -> ty::PolyFnSig<'tcx> {
2474 let tcx = self.tcx();
2475 let bound_vars = tcx.late_bound_vars(hir_id);
2476 debug!(?bound_vars);
2478 // We proactively collect all the inferred type params to emit a single error per fn def.
2479 let mut visitor = PlaceholderHirTyCollector::default();
2480 for ty in decl.inputs {
2481 visitor.visit_ty(ty);
2483 walk_generics(&mut visitor, generics);
2485 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2486 let output_ty = match decl.output {
2487 hir::FnRetTy::Return(ref output) => {
2488 visitor.visit_ty(output);
2489 self.ast_ty_to_ty(output)
2491 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2494 debug!("ty_of_fn: output_ty={:?}", output_ty);
2496 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi);
2497 let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
2499 if !self.allow_ty_infer() {
2500 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2501 // only want to emit an error complaining about them if infer types (`_`) are not
2502 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2503 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2505 crate::collect::placeholder_type_error(
2507 ident_span.map(|sp| sp.shrink_to_hi()),
2516 // Find any late-bound regions declared in return type that do
2517 // not appear in the arguments. These are not well-formed.
2520 // for<'a> fn() -> &'a str <-- 'a is bad
2521 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2522 let inputs = bare_fn_ty.inputs();
2523 let late_bound_in_args =
2524 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2525 let output = bare_fn_ty.output();
2526 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2528 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2533 "return type references {}, which is not constrained by the fn input types",
2541 fn validate_late_bound_regions(
2543 constrained_regions: FxHashSet<ty::BoundRegionKind>,
2544 referenced_regions: FxHashSet<ty::BoundRegionKind>,
2545 generate_err: impl Fn(&str) -> rustc_errors::DiagnosticBuilder<'tcx>,
2547 for br in referenced_regions.difference(&constrained_regions) {
2548 let br_name = match *br {
2549 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
2550 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2553 let mut err = generate_err(&br_name);
2555 if let ty::BrAnon(_) = *br {
2556 // The only way for an anonymous lifetime to wind up
2557 // in the return type but **also** be unconstrained is
2558 // if it only appears in "associated types" in the
2559 // input. See #47511 and #62200 for examples. In this case,
2560 // though we can easily give a hint that ought to be
2563 "lifetimes appearing in an associated type are not considered constrained",
2571 /// Given the bounds on an object, determines what single region bound (if any) we can
2572 /// use to summarize this type. The basic idea is that we will use the bound the user
2573 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2574 /// for region bounds. It may be that we can derive no bound at all, in which case
2575 /// we return `None`.
2576 fn compute_object_lifetime_bound(
2579 existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2580 ) -> Option<ty::Region<'tcx>> // if None, use the default
2582 let tcx = self.tcx();
2584 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2586 // No explicit region bound specified. Therefore, examine trait
2587 // bounds and see if we can derive region bounds from those.
2588 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2590 // If there are no derived region bounds, then report back that we
2591 // can find no region bound. The caller will use the default.
2592 if derived_region_bounds.is_empty() {
2596 // If any of the derived region bounds are 'static, that is always
2598 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2599 return Some(tcx.lifetimes.re_static);
2602 // Determine whether there is exactly one unique region in the set
2603 // of derived region bounds. If so, use that. Otherwise, report an
2605 let r = derived_region_bounds[0];
2606 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2607 tcx.sess.emit_err(AmbiguousLifetimeBound { span });