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_ast::TraitObjectSyntax;
17 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
18 use rustc_errors::{struct_span_err, Applicability, ErrorReported, FatalError};
20 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
21 use rustc_hir::def_id::{DefId, LocalDefId};
22 use rustc_hir::intravisit::{walk_generics, Visitor as _};
23 use rustc_hir::lang_items::LangItem;
24 use rustc_hir::{GenericArg, GenericArgs};
25 use rustc_middle::ty::subst::{self, GenericArgKind, InternalSubsts, Subst, SubstsRef};
26 use rustc_middle::ty::GenericParamDefKind;
27 use rustc_middle::ty::{self, Const, DefIdTree, Ty, TyCtxt, TypeFoldable};
28 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, BARE_TRAIT_OBJECTS};
29 use rustc_span::edition::Edition;
30 use rustc_span::lev_distance::find_best_match_for_name;
31 use rustc_span::symbol::{Ident, Symbol};
32 use rustc_span::{Span, DUMMY_SP};
33 use rustc_target::spec::abi;
34 use rustc_trait_selection::traits;
35 use rustc_trait_selection::traits::astconv_object_safety_violations;
36 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
37 use rustc_trait_selection::traits::wf::object_region_bounds;
39 use smallvec::SmallVec;
40 use std::collections::BTreeSet;
44 pub struct PathSeg(pub DefId, pub usize);
46 pub trait AstConv<'tcx> {
47 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
49 fn item_def_id(&self) -> Option<DefId>;
51 /// Returns predicates in scope of the form `X: Foo<T>`, where `X`
52 /// is a type parameter `X` with the given id `def_id` and T
53 /// matches `assoc_name`. This is a subset of the full set of
56 /// This is used for one specific purpose: resolving "short-hand"
57 /// associated type references like `T::Item`. In principle, we
58 /// would do that by first getting the full set of predicates in
59 /// scope and then filtering down to find those that apply to `T`,
60 /// but this can lead to cycle errors. The problem is that we have
61 /// to do this resolution *in order to create the predicates in
62 /// the first place*. Hence, we have this "special pass".
63 fn get_type_parameter_bounds(
68 ) -> ty::GenericPredicates<'tcx>;
70 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
71 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
72 -> Option<ty::Region<'tcx>>;
74 /// Returns the type to use when a type is omitted.
75 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
77 /// Returns `true` if `_` is allowed in type signatures in the current context.
78 fn allow_ty_infer(&self) -> bool;
80 /// Returns the const to use when a const is omitted.
84 param: Option<&ty::GenericParamDef>,
86 ) -> &'tcx Const<'tcx>;
88 /// Projecting an associated type from a (potentially)
89 /// higher-ranked trait reference is more complicated, because of
90 /// the possibility of late-bound regions appearing in the
91 /// associated type binding. This is not legal in function
92 /// signatures for that reason. In a function body, we can always
93 /// handle it because we can use inference variables to remove the
94 /// late-bound regions.
95 fn projected_ty_from_poly_trait_ref(
99 item_segment: &hir::PathSegment<'_>,
100 poly_trait_ref: ty::PolyTraitRef<'tcx>,
103 /// Normalize an associated type coming from the user.
104 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
106 /// Invoked when we encounter an error from some prior pass
107 /// (e.g., resolve) that is translated into a ty-error. This is
108 /// used to help suppress derived errors typeck might otherwise
110 fn set_tainted_by_errors(&self);
112 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
116 struct ConvertedBinding<'a, 'tcx> {
119 kind: ConvertedBindingKind<'a, 'tcx>,
120 gen_args: &'a GenericArgs<'a>,
125 enum ConvertedBindingKind<'a, 'tcx> {
127 Constraint(&'a [hir::GenericBound<'a>]),
130 /// New-typed boolean indicating whether explicit late-bound lifetimes
131 /// are present in a set of generic arguments.
133 /// For example if we have some method `fn f<'a>(&'a self)` implemented
134 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
135 /// is late-bound so should not be provided explicitly. Thus, if `f` is
136 /// instantiated with some generic arguments providing `'a` explicitly,
137 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
138 /// can provide an appropriate diagnostic later.
139 #[derive(Copy, Clone, PartialEq)]
140 pub enum ExplicitLateBound {
145 #[derive(Copy, Clone, PartialEq)]
146 pub enum IsMethodCall {
151 /// Denotes the "position" of a generic argument, indicating if it is a generic type,
152 /// generic function or generic method call.
153 #[derive(Copy, Clone, PartialEq)]
154 pub(crate) enum GenericArgPosition {
156 Value, // e.g., functions
160 /// A marker denoting that the generic arguments that were
161 /// provided did not match the respective generic parameters.
162 #[derive(Clone, Default)]
163 pub struct GenericArgCountMismatch {
164 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
165 pub reported: Option<ErrorReported>,
166 /// A list of spans of arguments provided that were not valid.
167 pub invalid_args: Vec<Span>,
170 /// Decorates the result of a generic argument count mismatch
171 /// check with whether explicit late bounds were provided.
173 pub struct GenericArgCountResult {
174 pub explicit_late_bound: ExplicitLateBound,
175 pub correct: Result<(), GenericArgCountMismatch>,
178 pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> {
179 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
183 param: &ty::GenericParamDef,
184 arg: &GenericArg<'_>,
185 ) -> subst::GenericArg<'tcx>;
189 substs: Option<&[subst::GenericArg<'tcx>]>,
190 param: &ty::GenericParamDef,
192 ) -> subst::GenericArg<'tcx>;
195 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
196 #[tracing::instrument(level = "debug", skip(self))]
197 pub fn ast_region_to_region(
199 lifetime: &hir::Lifetime,
200 def: Option<&ty::GenericParamDef>,
201 ) -> ty::Region<'tcx> {
202 let tcx = self.tcx();
203 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
205 let r = match tcx.named_region(lifetime.hir_id) {
206 Some(rl::Region::Static) => tcx.lifetimes.re_static,
208 Some(rl::Region::LateBound(debruijn, index, def_id, _)) => {
209 let name = lifetime_name(def_id.expect_local());
210 let br = ty::BoundRegion {
211 var: ty::BoundVar::from_u32(index),
212 kind: ty::BrNamed(def_id, name),
214 tcx.mk_region(ty::ReLateBound(debruijn, br))
217 Some(rl::Region::LateBoundAnon(debruijn, index, anon_index)) => {
218 let br = ty::BoundRegion {
219 var: ty::BoundVar::from_u32(index),
220 kind: ty::BrAnon(anon_index),
222 tcx.mk_region(ty::ReLateBound(debruijn, br))
225 Some(rl::Region::EarlyBound(index, id, _)) => {
226 let name = lifetime_name(id.expect_local());
227 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
230 Some(rl::Region::Free(scope, id)) => {
231 let name = lifetime_name(id.expect_local());
232 tcx.mk_region(ty::ReFree(ty::FreeRegion {
234 bound_region: ty::BrNamed(id, name),
237 // (*) -- not late-bound, won't change
241 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
242 debug!(?lifetime, "unelided lifetime in signature");
244 // This indicates an illegal lifetime
245 // elision. `resolve_lifetime` should have
246 // reported an error in this case -- but if
247 // not, let's error out.
248 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
250 // Supply some dummy value. We don't have an
251 // `re_error`, annoyingly, so use `'static`.
252 tcx.lifetimes.re_static
257 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
262 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
263 /// returns an appropriate set of substitutions for this particular reference to `I`.
264 pub fn ast_path_substs_for_ty(
268 item_segment: &hir::PathSegment<'_>,
269 ) -> SubstsRef<'tcx> {
270 let (substs, _) = self.create_substs_for_ast_path(
276 item_segment.infer_args,
279 let assoc_bindings = self.create_assoc_bindings_for_generic_args(item_segment.args());
281 if let Some(b) = assoc_bindings.first() {
282 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
288 /// Given the type/lifetime/const arguments provided to some path (along with
289 /// an implicit `Self`, if this is a trait reference), returns the complete
290 /// set of substitutions. This may involve applying defaulted type parameters.
291 /// Also returns back constraints on associated types.
296 /// T: std::ops::Index<usize, Output = u32>
297 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
300 /// 1. The `self_ty` here would refer to the type `T`.
301 /// 2. The path in question is the path to the trait `std::ops::Index`,
302 /// which will have been resolved to a `def_id`
303 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
304 /// parameters are returned in the `SubstsRef`, the associated type bindings like
305 /// `Output = u32` are returned in the `Vec<ConvertedBinding...>` result.
307 /// Note that the type listing given here is *exactly* what the user provided.
309 /// For (generic) associated types
312 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
315 /// We have the parent substs are the substs for the parent trait:
316 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
317 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
318 /// lists: `[Vec<u8>, u8, 'a]`.
319 #[tracing::instrument(level = "debug", skip(self, span))]
320 fn create_substs_for_ast_path<'a>(
324 parent_substs: &[subst::GenericArg<'tcx>],
325 seg: &hir::PathSegment<'_>,
326 generic_args: &'a hir::GenericArgs<'_>,
328 self_ty: Option<Ty<'tcx>>,
329 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
330 // If the type is parameterized by this region, then replace this
331 // region with the current anon region binding (in other words,
332 // whatever & would get replaced with).
334 let tcx = self.tcx();
335 let generics = tcx.generics_of(def_id);
336 debug!("generics: {:?}", generics);
338 if generics.has_self {
339 if generics.parent.is_some() {
340 // The parent is a trait so it should have at least one subst
341 // for the `Self` type.
342 assert!(!parent_substs.is_empty())
344 // This item (presumably a trait) needs a self-type.
345 assert!(self_ty.is_some());
348 assert!(self_ty.is_none() && parent_substs.is_empty());
351 let arg_count = Self::check_generic_arg_count(
358 GenericArgPosition::Type,
363 // Skip processing if type has no generic parameters.
364 // Traits always have `Self` as a generic parameter, which means they will not return early
365 // here and so associated type bindings will be handled regardless of whether there are any
366 // non-`Self` generic parameters.
367 if generics.params.is_empty() {
368 return (tcx.intern_substs(&[]), arg_count);
371 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
373 struct SubstsForAstPathCtxt<'a, 'tcx> {
374 astconv: &'a (dyn AstConv<'tcx> + 'a),
376 generic_args: &'a GenericArgs<'a>,
378 missing_type_params: Vec<String>,
379 inferred_params: Vec<Span>,
384 impl<'tcx, 'a> SubstsForAstPathCtxt<'tcx, 'a> {
385 fn default_needs_object_self(&mut self, param: &ty::GenericParamDef) -> bool {
386 let tcx = self.astconv.tcx();
387 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
388 if self.is_object && has_default {
389 let default_ty = tcx.at(self.span).type_of(param.def_id);
390 let self_param = tcx.types.self_param;
391 if default_ty.walk(tcx).any(|arg| arg == self_param.into()) {
392 // There is no suitable inference default for a type parameter
393 // that references self, in an object type.
403 impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> {
404 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) {
405 if did == self.def_id {
406 (Some(self.generic_args), self.infer_args)
408 // The last component of this tuple is unimportant.
415 param: &ty::GenericParamDef,
416 arg: &GenericArg<'_>,
417 ) -> subst::GenericArg<'tcx> {
418 let tcx = self.astconv.tcx();
420 let mut handle_ty_args = |has_default, ty: &hir::Ty<'_>| {
422 tcx.check_optional_stability(
428 // Default generic parameters may not be marked
429 // with stability attributes, i.e. when the
430 // default parameter was defined at the same time
431 // as the rest of the type. As such, we ignore missing
432 // stability attributes.
436 if let (hir::TyKind::Infer, false) = (&ty.kind, self.astconv.allow_ty_infer()) {
437 self.inferred_params.push(ty.span);
438 tcx.ty_error().into()
440 self.astconv.ast_ty_to_ty(ty).into()
444 match (¶m.kind, arg) {
445 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
446 self.astconv.ast_region_to_region(lt, Some(param)).into()
448 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
449 handle_ty_args(has_default, ty)
451 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
452 handle_ty_args(has_default, &inf.to_ty())
454 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
455 ty::Const::from_opt_const_arg_anon_const(
457 ty::WithOptConstParam {
458 did: tcx.hir().local_def_id(ct.value.hir_id),
459 const_param_did: Some(param.def_id),
464 (&GenericParamDefKind::Const { .. }, hir::GenericArg::Infer(inf)) => {
465 let ty = tcx.at(self.span).type_of(param.def_id);
466 if self.astconv.allow_ty_infer() {
467 self.astconv.ct_infer(ty, Some(param), inf.span).into()
469 self.inferred_params.push(inf.span);
470 tcx.const_error(ty).into()
479 substs: Option<&[subst::GenericArg<'tcx>]>,
480 param: &ty::GenericParamDef,
482 ) -> subst::GenericArg<'tcx> {
483 let tcx = self.astconv.tcx();
485 GenericParamDefKind::Lifetime => tcx.lifetimes.re_static.into(),
486 GenericParamDefKind::Type { has_default, .. } => {
487 if !infer_args && has_default {
488 // No type parameter provided, but a default exists.
490 // If we are converting an object type, then the
491 // `Self` parameter is unknown. However, some of the
492 // other type parameters may reference `Self` in their
493 // defaults. This will lead to an ICE if we are not
495 if self.default_needs_object_self(param) {
496 self.missing_type_params.push(param.name.to_string());
497 tcx.ty_error().into()
499 // This is a default type parameter.
500 let substs = substs.unwrap();
501 if substs.iter().any(|arg| match arg.unpack() {
502 GenericArgKind::Type(ty) => ty.references_error(),
505 // Avoid ICE #86756 when type error recovery goes awry.
506 return tcx.ty_error().into();
511 tcx.at(self.span).type_of(param.def_id).subst_spanned(
519 } else if infer_args {
520 // No type parameters were provided, we can infer all.
521 let param = if !self.default_needs_object_self(param) {
526 self.astconv.ty_infer(param, self.span).into()
528 // We've already errored above about the mismatch.
529 tcx.ty_error().into()
532 GenericParamDefKind::Const { has_default } => {
533 let ty = tcx.at(self.span).type_of(param.def_id);
534 if !infer_args && has_default {
535 tcx.const_param_default(param.def_id)
536 .subst_spanned(tcx, substs.unwrap(), Some(self.span))
540 self.astconv.ct_infer(ty, Some(param), self.span).into()
542 // We've already errored above about the mismatch.
543 tcx.const_error(ty).into()
551 let mut substs_ctx = SubstsForAstPathCtxt {
556 missing_type_params: vec![],
557 inferred_params: vec![],
561 let substs = Self::create_substs_for_generic_args(
571 self.complain_about_missing_type_params(
572 substs_ctx.missing_type_params,
575 generic_args.args.is_empty(),
579 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
580 generics, self_ty, substs
586 fn create_assoc_bindings_for_generic_args<'a>(
588 generic_args: &'a hir::GenericArgs<'_>,
589 ) -> Vec<ConvertedBinding<'a, 'tcx>> {
590 // Convert associated-type bindings or constraints into a separate vector.
591 // Example: Given this:
593 // T: Iterator<Item = u32>
595 // The `T` is passed in as a self-type; the `Item = u32` is
596 // not a "type parameter" of the `Iterator` trait, but rather
597 // a restriction on `<T as Iterator>::Item`, so it is passed
599 let assoc_bindings = generic_args
603 let kind = match binding.kind {
604 hir::TypeBindingKind::Equality { ty } => {
605 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty))
607 hir::TypeBindingKind::Constraint { bounds } => {
608 ConvertedBindingKind::Constraint(bounds)
612 hir_id: binding.hir_id,
613 item_name: binding.ident,
615 gen_args: binding.gen_args,
624 crate fn create_substs_for_associated_item(
629 item_segment: &hir::PathSegment<'_>,
630 parent_substs: SubstsRef<'tcx>,
631 ) -> SubstsRef<'tcx> {
633 "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}",
634 span, item_def_id, item_segment
636 if tcx.generics_of(item_def_id).params.is_empty() {
637 self.prohibit_generics(slice::from_ref(item_segment));
641 self.create_substs_for_ast_path(
647 item_segment.infer_args,
654 /// Instantiates the path for the given trait reference, assuming that it's
655 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
656 /// The type _cannot_ be a type other than a trait type.
658 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
659 /// are disallowed. Otherwise, they are pushed onto the vector given.
660 pub fn instantiate_mono_trait_ref(
662 trait_ref: &hir::TraitRef<'_>,
664 ) -> ty::TraitRef<'tcx> {
665 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
667 self.ast_path_to_mono_trait_ref(
669 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
671 trait_ref.path.segments.last().unwrap(),
675 fn instantiate_poly_trait_ref_inner(
679 binding_span: Option<Span>,
680 constness: ty::BoundConstness,
681 bounds: &mut Bounds<'tcx>,
683 trait_ref_span: Span,
685 trait_segment: &hir::PathSegment<'_>,
686 args: &GenericArgs<'_>,
689 ) -> GenericArgCountResult {
690 let (substs, arg_count) = self.create_substs_for_ast_path(
700 let tcx = self.tcx();
701 let bound_vars = tcx.late_bound_vars(hir_id);
704 let assoc_bindings = self.create_assoc_bindings_for_generic_args(args);
707 ty::Binder::bind_with_vars(ty::TraitRef::new(trait_def_id, substs), bound_vars);
709 debug!(?poly_trait_ref, ?assoc_bindings);
710 bounds.trait_bounds.push((poly_trait_ref, span, constness));
712 let mut dup_bindings = FxHashMap::default();
713 for binding in &assoc_bindings {
714 // Specify type to assert that error was already reported in `Err` case.
715 let _: Result<_, ErrorReported> = self.add_predicates_for_ast_type_binding(
722 binding_span.unwrap_or(binding.span),
724 // Okay to ignore `Err` because of `ErrorReported` (see above).
730 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
731 /// a full trait reference. The resulting trait reference is returned. This may also generate
732 /// auxiliary bounds, which are added to `bounds`.
737 /// poly_trait_ref = Iterator<Item = u32>
741 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
743 /// **A note on binders:** against our usual convention, there is an implied bounder around
744 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
745 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
746 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
747 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
749 #[tracing::instrument(level = "debug", skip(self, span, constness, bounds, speculative))]
750 pub(crate) fn instantiate_poly_trait_ref(
752 trait_ref: &hir::TraitRef<'_>,
754 constness: ty::BoundConstness,
756 bounds: &mut Bounds<'tcx>,
758 ) -> GenericArgCountResult {
759 let hir_id = trait_ref.hir_ref_id;
760 let binding_span = None;
761 let trait_ref_span = trait_ref.path.span;
762 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
763 let trait_segment = trait_ref.path.segments.last().unwrap();
764 let args = trait_segment.args();
765 let infer_args = trait_segment.infer_args;
767 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
768 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
770 self.instantiate_poly_trait_ref_inner(
786 pub(crate) fn instantiate_lang_item_trait_ref(
788 lang_item: hir::LangItem,
791 args: &GenericArgs<'_>,
793 bounds: &mut Bounds<'tcx>,
795 let binding_span = Some(span);
796 let constness = ty::BoundConstness::NotConst;
797 let speculative = false;
798 let trait_ref_span = span;
799 let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
800 let trait_segment = &hir::PathSegment::invalid();
801 let infer_args = false;
803 self.instantiate_poly_trait_ref_inner(
819 fn ast_path_to_mono_trait_ref(
824 trait_segment: &hir::PathSegment<'_>,
825 ) -> ty::TraitRef<'tcx> {
827 self.create_substs_for_ast_trait_ref(span, trait_def_id, self_ty, trait_segment);
828 let assoc_bindings = self.create_assoc_bindings_for_generic_args(trait_segment.args());
829 if let Some(b) = assoc_bindings.first() {
830 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
832 ty::TraitRef::new(trait_def_id, substs)
835 #[tracing::instrument(level = "debug", skip(self, span))]
836 fn create_substs_for_ast_trait_ref<'a>(
841 trait_segment: &'a hir::PathSegment<'a>,
842 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
843 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment);
845 self.create_substs_for_ast_path(
850 trait_segment.args(),
851 trait_segment.infer_args,
856 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
858 .associated_items(trait_def_id)
859 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
863 // Sets `implicitly_sized` to true on `Bounds` if necessary
864 pub(crate) fn add_implicitly_sized<'hir>(
866 bounds: &mut Bounds<'hir>,
867 ast_bounds: &'hir [hir::GenericBound<'hir>],
868 self_ty_where_predicates: Option<(hir::HirId, &'hir [hir::WherePredicate<'hir>])>,
871 let tcx = self.tcx();
873 // Try to find an unbound in bounds.
874 let mut unbound = None;
875 let mut search_bounds = |ast_bounds: &'hir [hir::GenericBound<'hir>]| {
876 for ab in ast_bounds {
877 if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab {
878 if unbound.is_none() {
879 unbound = Some(&ptr.trait_ref);
881 tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span });
886 search_bounds(ast_bounds);
887 if let Some((self_ty, where_clause)) = self_ty_where_predicates {
888 let self_ty_def_id = tcx.hir().local_def_id(self_ty).to_def_id();
889 for clause in where_clause {
890 if let hir::WherePredicate::BoundPredicate(pred) = clause {
891 match pred.bounded_ty.kind {
892 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => match path.res {
893 Res::Def(DefKind::TyParam, def_id) if def_id == self_ty_def_id => {}
898 search_bounds(pred.bounds);
903 let sized_def_id = tcx.lang_items().require(LangItem::Sized);
904 match (&sized_def_id, unbound) {
905 (Ok(sized_def_id), Some(tpb))
906 if tpb.path.res == Res::Def(DefKind::Trait, *sized_def_id) =>
908 // There was in fact a `?Sized` bound, return without doing anything
912 // There was a `?Trait` bound, but it was not `?Sized`; warn.
915 "default bound relaxed for a type parameter, but \
916 this does nothing because the given bound is not \
917 a default; only `?Sized` is supported",
919 // Otherwise, add implicitly sized if `Sized` is available.
922 // There was no `?Sized` bound; add implicitly sized if `Sized` is available.
925 if sized_def_id.is_err() {
926 // No lang item for `Sized`, so we can't add it as a bound.
929 bounds.implicitly_sized = Some(span);
932 /// This helper takes a *converted* parameter type (`param_ty`)
933 /// and an *unconverted* list of bounds:
937 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
939 /// `param_ty`, in ty form
942 /// It adds these `ast_bounds` into the `bounds` structure.
944 /// **A note on binders:** there is an implied binder around
945 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
946 /// for more details.
947 #[tracing::instrument(level = "debug", skip(self, ast_bounds, bounds))]
948 pub(crate) fn add_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'hir>>>(
952 bounds: &mut Bounds<'tcx>,
953 bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
955 for ast_bound in ast_bounds {
957 hir::GenericBound::Trait(poly_trait_ref, modifier) => {
958 let constness = match modifier {
959 hir::TraitBoundModifier::MaybeConst => ty::BoundConstness::ConstIfConst,
960 hir::TraitBoundModifier::None => ty::BoundConstness::NotConst,
961 hir::TraitBoundModifier::Maybe => continue,
964 let _ = self.instantiate_poly_trait_ref(
965 &poly_trait_ref.trait_ref,
973 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
974 self.instantiate_lang_item_trait_ref(
975 lang_item, span, hir_id, args, param_ty, bounds,
978 hir::GenericBound::Outlives(lifetime) => {
979 let region = self.ast_region_to_region(lifetime, None);
982 .push((ty::Binder::bind_with_vars(region, bound_vars), lifetime.span));
988 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
989 /// The self-type for the bounds is given by `param_ty`.
994 /// fn foo<T: Bar + Baz>() { }
995 /// ^ ^^^^^^^^^ ast_bounds
999 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1000 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1001 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1003 /// `span` should be the declaration size of the parameter.
1004 pub(crate) fn compute_bounds(
1007 ast_bounds: &[hir::GenericBound<'_>],
1009 self.compute_bounds_inner(param_ty, ast_bounds)
1012 /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type
1013 /// named `assoc_name` into ty::Bounds. Ignore the rest.
1014 pub(crate) fn compute_bounds_that_match_assoc_type(
1017 ast_bounds: &[hir::GenericBound<'_>],
1020 let mut result = Vec::new();
1022 for ast_bound in ast_bounds {
1023 if let Some(trait_ref) = ast_bound.trait_ref() {
1024 if let Some(trait_did) = trait_ref.trait_def_id() {
1025 if self.tcx().trait_may_define_assoc_type(trait_did, assoc_name) {
1026 result.push(ast_bound.clone());
1032 self.compute_bounds_inner(param_ty, &result)
1035 fn compute_bounds_inner(
1038 ast_bounds: &[hir::GenericBound<'_>],
1040 let mut bounds = Bounds::default();
1042 self.add_bounds(param_ty, ast_bounds.iter(), &mut bounds, ty::List::empty());
1047 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1050 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1051 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1052 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1053 #[tracing::instrument(
1055 skip(self, bounds, speculative, dup_bindings, path_span)
1057 fn add_predicates_for_ast_type_binding(
1059 hir_ref_id: hir::HirId,
1060 trait_ref: ty::PolyTraitRef<'tcx>,
1061 binding: &ConvertedBinding<'_, 'tcx>,
1062 bounds: &mut Bounds<'tcx>,
1064 dup_bindings: &mut FxHashMap<DefId, Span>,
1066 ) -> Result<(), ErrorReported> {
1067 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1068 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1069 // subtle in the event that `T` is defined in a supertrait of
1070 // `SomeTrait`, because in that case we need to upcast.
1072 // That is, consider this case:
1075 // trait SubTrait: SuperTrait<i32> { }
1076 // trait SuperTrait<A> { type T; }
1078 // ... B: SubTrait<T = foo> ...
1081 // We want to produce `<B as SuperTrait<i32>>::T == foo`.
1083 let tcx = self.tcx();
1086 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1087 // Simple case: X is defined in the current trait.
1090 // Otherwise, we have to walk through the supertraits to find
1092 self.one_bound_for_assoc_type(
1093 || traits::supertraits(tcx, trait_ref),
1094 || trait_ref.print_only_trait_path().to_string(),
1097 || match binding.kind {
1098 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1104 let (assoc_ident, def_scope) =
1105 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1107 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1108 // of calling `filter_by_name_and_kind`.
1110 .associated_items(candidate.def_id())
1111 .filter_by_name_unhygienic(assoc_ident.name)
1113 i.kind == ty::AssocKind::Type && i.ident.normalize_to_macros_2_0() == assoc_ident
1115 .expect("missing associated type");
1117 if !assoc_ty.vis.is_accessible_from(def_scope, tcx) {
1121 &format!("associated type `{}` is private", binding.item_name),
1123 .span_label(binding.span, "private associated type")
1126 tcx.check_stability(assoc_ty.def_id, Some(hir_ref_id), binding.span, None);
1130 .entry(assoc_ty.def_id)
1131 .and_modify(|prev_span| {
1132 self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified {
1134 prev_span: *prev_span,
1135 item_name: binding.item_name,
1136 def_path: tcx.def_path_str(assoc_ty.container.id()),
1139 .or_insert(binding.span);
1142 // Include substitutions for generic parameters of associated types
1143 let projection_ty = candidate.map_bound(|trait_ref| {
1144 let ident = Ident::new(assoc_ty.ident.name, binding.item_name.span);
1145 let item_segment = hir::PathSegment {
1147 hir_id: Some(binding.hir_id),
1149 args: Some(binding.gen_args),
1153 let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item(
1162 "add_predicates_for_ast_type_binding: substs for trait-ref and assoc_item: {:?}",
1163 substs_trait_ref_and_assoc_item
1167 item_def_id: assoc_ty.def_id,
1168 substs: substs_trait_ref_and_assoc_item,
1173 // Find any late-bound regions declared in `ty` that are not
1174 // declared in the trait-ref or assoc_ty. These are not well-formed.
1178 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1179 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1180 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1181 let late_bound_in_trait_ref =
1182 tcx.collect_constrained_late_bound_regions(&projection_ty);
1183 let late_bound_in_ty =
1184 tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty));
1185 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1186 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1188 // FIXME: point at the type params that don't have appropriate lifetimes:
1189 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1190 // ---- ---- ^^^^^^^
1191 self.validate_late_bound_regions(
1192 late_bound_in_trait_ref,
1199 "binding for associated type `{}` references {}, \
1200 which does not appear in the trait input types",
1209 match binding.kind {
1210 ConvertedBindingKind::Equality(ty) => {
1211 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1212 // the "projection predicate" for:
1214 // `<T as Iterator>::Item = u32`
1215 bounds.projection_bounds.push((
1216 projection_ty.map_bound(|projection_ty| {
1218 "add_predicates_for_ast_type_binding: projection_ty {:?}, substs: {:?}",
1219 projection_ty, projection_ty.substs
1221 ty::ProjectionPredicate { projection_ty, ty }
1226 ConvertedBindingKind::Constraint(ast_bounds) => {
1227 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1229 // `<T as Iterator>::Item: Debug`
1231 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1232 // parameter to have a skipped binder.
1233 let param_ty = tcx.mk_ty(ty::Projection(projection_ty.skip_binder()));
1234 self.add_bounds(param_ty, ast_bounds.iter(), bounds, candidate.bound_vars());
1244 item_segment: &hir::PathSegment<'_>,
1246 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1247 self.normalize_ty(span, self.tcx().at(span).type_of(did).subst(self.tcx(), substs))
1250 fn conv_object_ty_poly_trait_ref(
1253 trait_bounds: &[hir::PolyTraitRef<'_>],
1254 lifetime: &hir::Lifetime,
1257 let tcx = self.tcx();
1259 let mut bounds = Bounds::default();
1260 let mut potential_assoc_types = Vec::new();
1261 let dummy_self = self.tcx().types.trait_object_dummy_self;
1262 for trait_bound in trait_bounds.iter().rev() {
1263 if let GenericArgCountResult {
1265 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1267 } = self.instantiate_poly_trait_ref(
1268 &trait_bound.trait_ref,
1270 ty::BoundConstness::NotConst,
1275 potential_assoc_types.extend(cur_potential_assoc_types);
1279 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1280 // is used and no 'maybe' bounds are used.
1281 let expanded_traits =
1282 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1283 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) =
1284 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1285 if regular_traits.len() > 1 {
1286 let first_trait = ®ular_traits[0];
1287 let additional_trait = ®ular_traits[1];
1288 let mut err = struct_span_err!(
1290 additional_trait.bottom().1,
1292 "only auto traits can be used as additional traits in a trait object"
1294 additional_trait.label_with_exp_info(
1296 "additional non-auto trait",
1299 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1301 "consider creating a new trait with all of these as supertraits and using that \
1302 trait here instead: `trait NewTrait: {} {{}}`",
1305 .map(|t| t.trait_ref().print_only_trait_path().to_string())
1306 .collect::<Vec<_>>()
1310 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1311 for more information on them, visit \
1312 <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1317 if regular_traits.is_empty() && auto_traits.is_empty() {
1318 tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span });
1319 return tcx.ty_error();
1322 // Check that there are no gross object safety violations;
1323 // most importantly, that the supertraits don't contain `Self`,
1325 for item in ®ular_traits {
1326 let object_safety_violations =
1327 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1328 if !object_safety_violations.is_empty() {
1329 report_object_safety_error(
1332 item.trait_ref().def_id(),
1333 &object_safety_violations,
1336 return tcx.ty_error();
1340 // Use a `BTreeSet` to keep output in a more consistent order.
1341 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1343 let regular_traits_refs_spans = bounds
1346 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1348 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1349 assert_eq!(constness, ty::BoundConstness::NotConst);
1351 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1353 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1354 obligation.predicate
1357 let bound_predicate = obligation.predicate.kind();
1358 match bound_predicate.skip_binder() {
1359 ty::PredicateKind::Trait(pred) => {
1360 let pred = bound_predicate.rebind(pred);
1361 associated_types.entry(span).or_default().extend(
1362 tcx.associated_items(pred.def_id())
1363 .in_definition_order()
1364 .filter(|item| item.kind == ty::AssocKind::Type)
1365 .map(|item| item.def_id),
1368 ty::PredicateKind::Projection(pred) => {
1369 let pred = bound_predicate.rebind(pred);
1370 // A `Self` within the original bound will be substituted with a
1371 // `trait_object_dummy_self`, so check for that.
1372 let references_self =
1373 pred.skip_binder().ty.walk(tcx).any(|arg| arg == dummy_self.into());
1375 // If the projection output contains `Self`, force the user to
1376 // elaborate it explicitly to avoid a lot of complexity.
1378 // The "classicaly useful" case is the following:
1380 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1385 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1386 // but actually supporting that would "expand" to an infinitely-long type
1387 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1389 // Instead, we force the user to write
1390 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1391 // the discussion in #56288 for alternatives.
1392 if !references_self {
1393 // Include projections defined on supertraits.
1394 bounds.projection_bounds.push((pred, span));
1402 for (projection_bound, _) in &bounds.projection_bounds {
1403 for def_ids in associated_types.values_mut() {
1404 def_ids.remove(&projection_bound.projection_def_id());
1408 self.complain_about_missing_associated_types(
1410 potential_assoc_types,
1414 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1415 // `dyn Trait + Send`.
1416 // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering
1418 let mut duplicates = FxHashSet::default();
1419 auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id()));
1420 debug!("regular_traits: {:?}", regular_traits);
1421 debug!("auto_traits: {:?}", auto_traits);
1423 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1424 let existential_trait_refs = regular_traits.iter().map(|i| {
1425 i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| {
1426 if trait_ref.self_ty() != dummy_self {
1427 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1428 // which picks up non-supertraits where clauses - but also, the object safety
1429 // completely ignores trait aliases, which could be object safety hazards. We
1430 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1431 // disabled. (#66420)
1432 tcx.sess.delay_span_bug(
1435 "trait_ref_to_existential called on {:?} with non-dummy Self",
1440 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1443 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1444 bound.map_bound(|b| {
1445 if b.projection_ty.self_ty() != dummy_self {
1446 tcx.sess.delay_span_bug(
1448 &format!("trait_ref_to_existential called on {:?} with non-dummy Self", b),
1451 ty::ExistentialProjection::erase_self_ty(tcx, b)
1455 let regular_trait_predicates = existential_trait_refs
1456 .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait));
1457 let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| {
1458 ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()))
1460 // N.b. principal, projections, auto traits
1461 // FIXME: This is actually wrong with multiple principals in regards to symbol mangling
1462 let mut v = regular_trait_predicates
1464 existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)),
1466 .chain(auto_trait_predicates)
1467 .collect::<SmallVec<[_; 8]>>();
1468 v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
1470 let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter());
1472 // Use explicitly-specified region bound.
1473 let region_bound = if !lifetime.is_elided() {
1474 self.ast_region_to_region(lifetime, None)
1476 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1477 if tcx.named_region(lifetime.hir_id).is_some() {
1478 self.ast_region_to_region(lifetime, None)
1480 self.re_infer(None, span).unwrap_or_else(|| {
1481 let mut err = struct_span_err!(
1485 "the lifetime bound for this object type cannot be deduced \
1486 from context; please supply an explicit bound"
1489 // We will have already emitted an error E0106 complaining about a
1490 // missing named lifetime in `&dyn Trait`, so we elide this one.
1495 tcx.lifetimes.re_static
1500 debug!("region_bound: {:?}", region_bound);
1502 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1503 debug!("trait_object_type: {:?}", ty);
1507 fn report_ambiguous_associated_type(
1514 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1515 if let (true, Ok(snippet)) = (
1518 .confused_type_with_std_module
1520 .any(|full_span| full_span.contains(span)),
1521 self.tcx().sess.source_map().span_to_snippet(span),
1523 err.span_suggestion(
1525 "you are looking for the module in `std`, not the primitive type",
1526 format!("std::{}", snippet),
1527 Applicability::MachineApplicable,
1530 err.span_suggestion(
1532 "use fully-qualified syntax",
1533 format!("<{} as {}>::{}", type_str, trait_str, name),
1534 Applicability::HasPlaceholders,
1540 // Search for a bound on a type parameter which includes the associated item
1541 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1542 // This function will fail if there are no suitable bounds or there is
1544 fn find_bound_for_assoc_item(
1546 ty_param_def_id: LocalDefId,
1549 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported> {
1550 let tcx = self.tcx();
1553 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1554 ty_param_def_id, assoc_name, span,
1557 let predicates = &self
1558 .get_type_parameter_bounds(span, ty_param_def_id.to_def_id(), assoc_name)
1561 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1563 let param_hir_id = tcx.hir().local_def_id_to_hir_id(ty_param_def_id);
1564 let param_name = tcx.hir().ty_param_name(param_hir_id);
1565 self.one_bound_for_assoc_type(
1567 traits::transitive_bounds_that_define_assoc_type(
1569 predicates.iter().filter_map(|(p, _)| {
1570 Some(p.to_opt_poly_trait_pred()?.map_bound(|t| t.trait_ref))
1575 || param_name.to_string(),
1582 // Checks that `bounds` contains exactly one element and reports appropriate
1583 // errors otherwise.
1584 fn one_bound_for_assoc_type<I>(
1586 all_candidates: impl Fn() -> I,
1587 ty_param_name: impl Fn() -> String,
1590 is_equality: impl Fn() -> Option<String>,
1591 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorReported>
1593 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1595 let mut matching_candidates = all_candidates()
1596 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1598 let bound = match matching_candidates.next() {
1599 Some(bound) => bound,
1601 self.complain_about_assoc_type_not_found(
1607 return Err(ErrorReported);
1611 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1613 if let Some(bound2) = matching_candidates.next() {
1614 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1616 let is_equality = is_equality();
1617 let bounds = IntoIterator::into_iter([bound, bound2]).chain(matching_candidates);
1618 let mut err = if is_equality.is_some() {
1619 // More specific Error Index entry.
1624 "ambiguous associated type `{}` in bounds of `{}`",
1633 "ambiguous associated type `{}` in bounds of `{}`",
1638 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1640 let mut where_bounds = vec![];
1641 for bound in bounds {
1642 let bound_id = bound.def_id();
1643 let bound_span = self
1645 .associated_items(bound_id)
1646 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
1647 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1649 if let Some(bound_span) = bound_span {
1653 "ambiguous `{}` from `{}`",
1655 bound.print_only_trait_path(),
1658 if let Some(constraint) = &is_equality {
1659 where_bounds.push(format!(
1660 " T: {trait}::{assoc} = {constraint}",
1661 trait=bound.print_only_trait_path(),
1663 constraint=constraint,
1666 err.span_suggestion_verbose(
1667 span.with_hi(assoc_name.span.lo()),
1668 "use fully qualified syntax to disambiguate",
1672 bound.print_only_trait_path(),
1674 Applicability::MaybeIncorrect,
1679 "associated type `{}` could derive from `{}`",
1681 bound.print_only_trait_path(),
1685 if !where_bounds.is_empty() {
1687 "consider introducing a new type parameter `T` and adding `where` constraints:\
1688 \n where\n T: {},\n{}",
1690 where_bounds.join(",\n"),
1694 if !where_bounds.is_empty() {
1695 return Err(ErrorReported);
1701 // Create a type from a path to an associated type.
1702 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1703 // and item_segment is the path segment for `D`. We return a type and a def for
1705 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1706 // parameter or `Self`.
1707 // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1708 // it should also start reportint the `BARE_TRAIT_OBJECTS` lint.
1709 pub fn associated_path_to_ty(
1711 hir_ref_id: hir::HirId,
1715 assoc_segment: &hir::PathSegment<'_>,
1716 permit_variants: bool,
1717 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorReported> {
1718 let tcx = self.tcx();
1719 let assoc_ident = assoc_segment.ident;
1721 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1723 // Check if we have an enum variant.
1724 let mut variant_resolution = None;
1725 if let ty::Adt(adt_def, _) = qself_ty.kind() {
1726 if adt_def.is_enum() {
1727 let variant_def = adt_def
1730 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident, adt_def.did));
1731 if let Some(variant_def) = variant_def {
1732 if permit_variants {
1733 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None);
1734 self.prohibit_generics(slice::from_ref(assoc_segment));
1735 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1737 variant_resolution = Some(variant_def.def_id);
1743 // Find the type of the associated item, and the trait where the associated
1744 // item is declared.
1745 let bound = match (&qself_ty.kind(), qself_res) {
1746 (_, Res::SelfTy(Some(_), Some((impl_def_id, _)))) => {
1747 // `Self` in an impl of a trait -- we have a concrete self type and a
1749 let trait_ref = match tcx.impl_trait_ref(impl_def_id) {
1750 Some(trait_ref) => trait_ref,
1752 // A cycle error occurred, most likely.
1753 return Err(ErrorReported);
1757 self.one_bound_for_assoc_type(
1758 || traits::supertraits(tcx, ty::Binder::dummy(trait_ref)),
1759 || "Self".to_string(),
1767 Res::SelfTy(Some(param_did), None) | Res::Def(DefKind::TyParam, param_did),
1768 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
1770 if variant_resolution.is_some() {
1771 // Variant in type position
1772 let msg = format!("expected type, found variant `{}`", assoc_ident);
1773 tcx.sess.span_err(span, &msg);
1774 } else if qself_ty.is_enum() {
1775 let mut err = struct_span_err!(
1779 "no variant named `{}` found for enum `{}`",
1784 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1785 if let Some(suggested_name) = find_best_match_for_name(
1789 .map(|variant| variant.ident.name)
1790 .collect::<Vec<Symbol>>(),
1794 err.span_suggestion(
1796 "there is a variant with a similar name",
1797 suggested_name.to_string(),
1798 Applicability::MaybeIncorrect,
1803 format!("variant not found in `{}`", qself_ty),
1807 if let Some(sp) = tcx.hir().span_if_local(adt_def.did) {
1808 let sp = tcx.sess.source_map().guess_head_span(sp);
1809 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1813 } else if !qself_ty.references_error() {
1814 // Don't print `TyErr` to the user.
1815 self.report_ambiguous_associated_type(
1817 &qself_ty.to_string(),
1822 return Err(ErrorReported);
1826 let trait_did = bound.def_id();
1827 let (assoc_ident, def_scope) =
1828 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1830 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1831 // of calling `filter_by_name_and_kind`.
1833 .associated_items(trait_did)
1834 .in_definition_order()
1836 i.kind.namespace() == Namespace::TypeNS
1837 && i.ident.normalize_to_macros_2_0() == assoc_ident
1839 .expect("missing associated type");
1841 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
1842 let ty = self.normalize_ty(span, ty);
1844 let kind = DefKind::AssocTy;
1845 if !item.vis.is_accessible_from(def_scope, tcx) {
1846 let kind = kind.descr(item.def_id);
1847 let msg = format!("{} `{}` is private", kind, assoc_ident);
1849 .struct_span_err(span, &msg)
1850 .span_label(span, &format!("private {}", kind))
1853 tcx.check_stability(item.def_id, Some(hir_ref_id), span, None);
1855 if let Some(variant_def_id) = variant_resolution {
1856 tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
1857 let mut err = lint.build("ambiguous associated item");
1858 let mut could_refer_to = |kind: DefKind, def_id, also| {
1859 let note_msg = format!(
1860 "`{}` could{} refer to the {} defined here",
1865 err.span_note(tcx.def_span(def_id), ¬e_msg);
1868 could_refer_to(DefKind::Variant, variant_def_id, "");
1869 could_refer_to(kind, item.def_id, " also");
1871 err.span_suggestion(
1873 "use fully-qualified syntax",
1874 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
1875 Applicability::MachineApplicable,
1881 Ok((ty, kind, item.def_id))
1887 opt_self_ty: Option<Ty<'tcx>>,
1889 trait_segment: &hir::PathSegment<'_>,
1890 item_segment: &hir::PathSegment<'_>,
1892 let tcx = self.tcx();
1894 let trait_def_id = tcx.parent(item_def_id).unwrap();
1896 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
1898 let Some(self_ty) = opt_self_ty else {
1899 let path_str = tcx.def_path_str(trait_def_id);
1901 let def_id = self.item_def_id();
1903 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
1905 let parent_def_id = def_id
1906 .and_then(|def_id| {
1907 def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
1909 .map(|hir_id| tcx.hir().get_parent_did(hir_id).to_def_id());
1911 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
1913 // If the trait in segment is the same as the trait defining the item,
1914 // use the `<Self as ..>` syntax in the error.
1915 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
1916 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
1918 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
1924 self.report_ambiguous_associated_type(
1928 item_segment.ident.name,
1930 return tcx.ty_error();
1933 debug!("qpath_to_ty: self_type={:?}", self_ty);
1935 let trait_ref = self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment);
1937 let item_substs = self.create_substs_for_associated_item(
1945 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
1947 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
1950 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
1954 let mut has_err = false;
1955 for segment in segments {
1956 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
1957 for arg in segment.args().args {
1958 let (span, kind) = match arg {
1959 hir::GenericArg::Lifetime(lt) => {
1965 (lt.span, "lifetime")
1967 hir::GenericArg::Type(ty) => {
1975 hir::GenericArg::Const(ct) => {
1983 hir::GenericArg::Infer(inf) => {
1989 (inf.span, "generic")
1992 let mut err = struct_span_err!(
1996 "{} arguments are not allowed for this type",
1999 err.span_label(span, format!("{} argument not allowed", kind));
2001 if err_for_lt && err_for_ty && err_for_ct {
2006 // Only emit the first error to avoid overloading the user with error messages.
2007 if let [binding, ..] = segment.args().bindings {
2009 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2015 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2016 pub fn def_ids_for_value_path_segments(
2018 segments: &[hir::PathSegment<'_>],
2019 self_ty: Option<Ty<'tcx>>,
2023 // We need to extract the type parameters supplied by the user in
2024 // the path `path`. Due to the current setup, this is a bit of a
2025 // tricky-process; the problem is that resolve only tells us the
2026 // end-point of the path resolution, and not the intermediate steps.
2027 // Luckily, we can (at least for now) deduce the intermediate steps
2028 // just from the end-point.
2030 // There are basically five cases to consider:
2032 // 1. Reference to a constructor of a struct:
2034 // struct Foo<T>(...)
2036 // In this case, the parameters are declared in the type space.
2038 // 2. Reference to a constructor of an enum variant:
2040 // enum E<T> { Foo(...) }
2042 // In this case, the parameters are defined in the type space,
2043 // but may be specified either on the type or the variant.
2045 // 3. Reference to a fn item or a free constant:
2049 // In this case, the path will again always have the form
2050 // `a::b::foo::<T>` where only the final segment should have
2051 // type parameters. However, in this case, those parameters are
2052 // declared on a value, and hence are in the `FnSpace`.
2054 // 4. Reference to a method or an associated constant:
2056 // impl<A> SomeStruct<A> {
2060 // Here we can have a path like
2061 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2062 // may appear in two places. The penultimate segment,
2063 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2064 // final segment, `foo::<B>` contains parameters in fn space.
2066 // The first step then is to categorize the segments appropriately.
2068 let tcx = self.tcx();
2070 assert!(!segments.is_empty());
2071 let last = segments.len() - 1;
2073 let mut path_segs = vec![];
2076 // Case 1. Reference to a struct constructor.
2077 DefKind::Ctor(CtorOf::Struct, ..) => {
2078 // Everything but the final segment should have no
2079 // parameters at all.
2080 let generics = tcx.generics_of(def_id);
2081 // Variant and struct constructors use the
2082 // generics of their parent type definition.
2083 let generics_def_id = generics.parent.unwrap_or(def_id);
2084 path_segs.push(PathSeg(generics_def_id, last));
2087 // Case 2. Reference to a variant constructor.
2088 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2089 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2090 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2091 debug_assert!(adt_def.is_enum());
2093 } else if last >= 1 && segments[last - 1].args.is_some() {
2094 // Everything but the penultimate segment should have no
2095 // parameters at all.
2096 let mut def_id = def_id;
2098 // `DefKind::Ctor` -> `DefKind::Variant`
2099 if let DefKind::Ctor(..) = kind {
2100 def_id = tcx.parent(def_id).unwrap()
2103 // `DefKind::Variant` -> `DefKind::Enum`
2104 let enum_def_id = tcx.parent(def_id).unwrap();
2105 (enum_def_id, last - 1)
2107 // FIXME: lint here recommending `Enum::<...>::Variant` form
2108 // instead of `Enum::Variant::<...>` form.
2110 // Everything but the final segment should have no
2111 // parameters at all.
2112 let generics = tcx.generics_of(def_id);
2113 // Variant and struct constructors use the
2114 // generics of their parent type definition.
2115 (generics.parent.unwrap_or(def_id), last)
2117 path_segs.push(PathSeg(generics_def_id, index));
2120 // Case 3. Reference to a top-level value.
2121 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static => {
2122 path_segs.push(PathSeg(def_id, last));
2125 // Case 4. Reference to a method or associated const.
2126 DefKind::AssocFn | DefKind::AssocConst => {
2127 if segments.len() >= 2 {
2128 let generics = tcx.generics_of(def_id);
2129 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2131 path_segs.push(PathSeg(def_id, last));
2134 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2137 debug!("path_segs = {:?}", path_segs);
2142 // Check a type `Path` and convert it to a `Ty`.
2145 opt_self_ty: Option<Ty<'tcx>>,
2146 path: &hir::Path<'_>,
2147 permit_variants: bool,
2149 let tcx = self.tcx();
2152 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2153 path.res, opt_self_ty, path.segments
2156 let span = path.span;
2158 Res::Def(DefKind::OpaqueTy, did) => {
2159 // Check for desugared `impl Trait`.
2160 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2161 let item_segment = path.segments.split_last().unwrap();
2162 self.prohibit_generics(item_segment.1);
2163 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2164 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2171 | DefKind::ForeignTy,
2174 assert_eq!(opt_self_ty, None);
2175 self.prohibit_generics(path.segments.split_last().unwrap().1);
2176 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2178 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2179 // Convert "variant type" as if it were a real type.
2180 // The resulting `Ty` is type of the variant's enum for now.
2181 assert_eq!(opt_self_ty, None);
2184 self.def_ids_for_value_path_segments(path.segments, None, kind, def_id);
2185 let generic_segs: FxHashSet<_> =
2186 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2187 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2189 if !generic_segs.contains(&index) { Some(seg) } else { None }
2193 let PathSeg(def_id, index) = path_segs.last().unwrap();
2194 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2196 Res::Def(DefKind::TyParam, def_id) => {
2197 assert_eq!(opt_self_ty, None);
2198 self.prohibit_generics(path.segments);
2200 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
2201 let item_id = tcx.hir().get_parent_node(hir_id);
2202 let item_def_id = tcx.hir().local_def_id(item_id);
2203 let generics = tcx.generics_of(item_def_id);
2204 let index = generics.param_def_id_to_index[&def_id];
2205 tcx.mk_ty_param(index, tcx.hir().name(hir_id))
2207 Res::SelfTy(Some(_), None) => {
2208 // `Self` in trait or type alias.
2209 assert_eq!(opt_self_ty, None);
2210 self.prohibit_generics(path.segments);
2211 tcx.types.self_param
2213 Res::SelfTy(_, Some((def_id, forbid_generic))) => {
2214 // `Self` in impl (we know the concrete type).
2215 assert_eq!(opt_self_ty, None);
2216 self.prohibit_generics(path.segments);
2217 // Try to evaluate any array length constants.
2218 let normalized_ty = self.normalize_ty(span, tcx.at(span).type_of(def_id));
2219 if forbid_generic && normalized_ty.definitely_needs_subst(tcx) {
2220 let mut err = tcx.sess.struct_span_err(
2222 "generic `Self` types are currently not permitted in anonymous constants",
2224 if let Some(hir::Node::Item(&hir::Item {
2225 kind: hir::ItemKind::Impl(ref impl_),
2227 })) = tcx.hir().get_if_local(def_id)
2229 err.span_note(impl_.self_ty.span, "not a concrete type");
2237 Res::Def(DefKind::AssocTy, def_id) => {
2238 debug_assert!(path.segments.len() >= 2);
2239 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2244 &path.segments[path.segments.len() - 2],
2245 path.segments.last().unwrap(),
2248 Res::PrimTy(prim_ty) => {
2249 assert_eq!(opt_self_ty, None);
2250 self.prohibit_generics(path.segments);
2252 hir::PrimTy::Bool => tcx.types.bool,
2253 hir::PrimTy::Char => tcx.types.char,
2254 hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2255 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2256 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2257 hir::PrimTy::Str => tcx.types.str_,
2261 self.set_tainted_by_errors();
2262 self.tcx().ty_error()
2264 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2268 /// Parses the programmer's textual representation of a type into our
2269 /// internal notion of a type.
2270 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2271 self.ast_ty_to_ty_inner(ast_ty, false, false)
2274 /// Parses the programmer's textual representation of a type into our
2275 /// internal notion of a type. This is meant to be used within a path.
2276 pub fn ast_ty_to_ty_in_path(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2277 self.ast_ty_to_ty_inner(ast_ty, false, true)
2280 /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2281 /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2282 #[tracing::instrument(level = "debug", skip(self))]
2283 fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool, in_path: bool) -> Ty<'tcx> {
2284 let tcx = self.tcx();
2286 let result_ty = match ast_ty.kind {
2287 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(ty)),
2288 hir::TyKind::Ptr(ref mt) => {
2289 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl })
2291 hir::TyKind::Rptr(ref region, ref mt) => {
2292 let r = self.ast_region_to_region(region, None);
2294 let t = self.ast_ty_to_ty_inner(mt.ty, true, false);
2295 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2297 hir::TyKind::Never => tcx.types.never,
2298 hir::TyKind::Tup(fields) => tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(t))),
2299 hir::TyKind::BareFn(bf) => {
2300 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span);
2302 tcx.mk_fn_ptr(self.ty_of_fn(
2307 &hir::Generics::empty(),
2312 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
2313 self.maybe_lint_bare_trait(ast_ty, in_path);
2314 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed)
2316 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2317 debug!(?maybe_qself, ?path);
2318 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2319 self.res_to_ty(opt_self_ty, path, false)
2321 hir::TyKind::OpaqueDef(item_id, lifetimes) => {
2322 let opaque_ty = tcx.hir().item(item_id);
2323 let def_id = item_id.def_id.to_def_id();
2325 match opaque_ty.kind {
2326 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => self
2327 .impl_trait_ty_to_ty(
2332 hir::OpaqueTyOrigin::FnReturn(..)
2333 | hir::OpaqueTyOrigin::AsyncFn(..)
2336 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2339 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2340 debug!(?qself, ?segment);
2341 let ty = self.ast_ty_to_ty_inner(qself, false, true);
2343 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = qself.kind {
2348 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2349 .map(|(ty, _, _)| ty)
2350 .unwrap_or_else(|_| tcx.ty_error())
2352 hir::TyKind::Path(hir::QPath::LangItem(lang_item, span, _)) => {
2353 let def_id = tcx.require_lang_item(lang_item, Some(span));
2354 let (substs, _) = self.create_substs_for_ast_path(
2358 &hir::PathSegment::invalid(),
2359 &GenericArgs::none(),
2363 self.normalize_ty(span, tcx.at(span).type_of(def_id).subst(tcx, substs))
2365 hir::TyKind::Array(ref ty, ref length) => {
2366 let length_def_id = tcx.hir().local_def_id(length.hir_id);
2367 let length = ty::Const::from_anon_const(tcx, length_def_id);
2368 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(ty), length));
2369 self.normalize_ty(ast_ty.span, array_ty)
2371 hir::TyKind::Typeof(ref e) => {
2372 tcx.sess.emit_err(TypeofReservedKeywordUsed { span: ast_ty.span });
2373 tcx.type_of(tcx.hir().local_def_id(e.hir_id))
2375 hir::TyKind::Infer => {
2376 // Infer also appears as the type of arguments or return
2377 // values in an ExprKind::Closure, or as
2378 // the type of local variables. Both of these cases are
2379 // handled specially and will not descend into this routine.
2380 self.ty_infer(None, ast_ty.span)
2382 hir::TyKind::Err => tcx.ty_error(),
2387 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2391 fn impl_trait_ty_to_ty(
2394 lifetimes: &[hir::GenericArg<'_>],
2395 replace_parent_lifetimes: bool,
2397 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2398 let tcx = self.tcx();
2400 let generics = tcx.generics_of(def_id);
2402 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2403 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2404 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2405 // Our own parameters are the resolved lifetimes.
2406 if let GenericParamDefKind::Lifetime = param.kind {
2407 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2408 self.ast_region_to_region(lifetime, None).into()
2417 // For RPIT (return position impl trait), only lifetimes
2418 // mentioned in the impl Trait predicate are captured by
2419 // the opaque type, so the lifetime parameters from the
2420 // parent item need to be replaced with `'static`.
2422 // For `impl Trait` in the types of statics, constants,
2423 // locals and type aliases. These capture all parent
2424 // lifetimes, so they can use their identity subst.
2425 GenericParamDefKind::Lifetime if replace_parent_lifetimes => {
2426 tcx.lifetimes.re_static.into()
2428 _ => tcx.mk_param_from_def(param),
2432 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2434 let ty = tcx.mk_opaque(def_id, substs);
2435 debug!("impl_trait_ty_to_ty: {}", ty);
2439 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2441 hir::TyKind::Infer if expected_ty.is_some() => {
2442 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2443 expected_ty.unwrap()
2445 _ => self.ast_ty_to_ty(ty),
2452 unsafety: hir::Unsafety,
2454 decl: &hir::FnDecl<'_>,
2455 generics: &hir::Generics<'_>,
2456 ident_span: Option<Span>,
2457 hir_ty: Option<&hir::Ty<'_>>,
2458 ) -> ty::PolyFnSig<'tcx> {
2461 let tcx = self.tcx();
2462 let bound_vars = tcx.late_bound_vars(hir_id);
2463 debug!(?bound_vars);
2465 // We proactively collect all the inferred type params to emit a single error per fn def.
2466 let mut visitor = PlaceholderHirTyCollector::default();
2467 for ty in decl.inputs {
2468 visitor.visit_ty(ty);
2470 walk_generics(&mut visitor, generics);
2472 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2473 let output_ty = match decl.output {
2474 hir::FnRetTy::Return(output) => {
2475 visitor.visit_ty(output);
2476 self.ast_ty_to_ty(output)
2478 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2481 debug!("ty_of_fn: output_ty={:?}", output_ty);
2483 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi);
2484 let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
2486 if !self.allow_ty_infer() {
2487 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2488 // only want to emit an error complaining about them if infer types (`_`) are not
2489 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2490 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2492 crate::collect::placeholder_type_error(
2494 ident_span.map(|sp| sp.shrink_to_hi()),
2503 // Find any late-bound regions declared in return type that do
2504 // not appear in the arguments. These are not well-formed.
2507 // for<'a> fn() -> &'a str <-- 'a is bad
2508 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2509 let inputs = bare_fn_ty.inputs();
2510 let late_bound_in_args =
2511 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2512 let output = bare_fn_ty.output();
2513 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2515 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2520 "return type references {}, which is not constrained by the fn input types",
2528 fn validate_late_bound_regions(
2530 constrained_regions: FxHashSet<ty::BoundRegionKind>,
2531 referenced_regions: FxHashSet<ty::BoundRegionKind>,
2532 generate_err: impl Fn(&str) -> rustc_errors::DiagnosticBuilder<'tcx>,
2534 for br in referenced_regions.difference(&constrained_regions) {
2535 let br_name = match *br {
2536 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
2537 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2540 let mut err = generate_err(&br_name);
2542 if let ty::BrAnon(_) = *br {
2543 // The only way for an anonymous lifetime to wind up
2544 // in the return type but **also** be unconstrained is
2545 // if it only appears in "associated types" in the
2546 // input. See #47511 and #62200 for examples. In this case,
2547 // though we can easily give a hint that ought to be
2550 "lifetimes appearing in an associated type are not considered constrained",
2558 /// Given the bounds on an object, determines what single region bound (if any) we can
2559 /// use to summarize this type. The basic idea is that we will use the bound the user
2560 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2561 /// for region bounds. It may be that we can derive no bound at all, in which case
2562 /// we return `None`.
2563 fn compute_object_lifetime_bound(
2566 existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2567 ) -> Option<ty::Region<'tcx>> // if None, use the default
2569 let tcx = self.tcx();
2571 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2573 // No explicit region bound specified. Therefore, examine trait
2574 // bounds and see if we can derive region bounds from those.
2575 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2577 // If there are no derived region bounds, then report back that we
2578 // can find no region bound. The caller will use the default.
2579 if derived_region_bounds.is_empty() {
2583 // If any of the derived region bounds are 'static, that is always
2585 if derived_region_bounds.iter().any(|&r| ty::ReStatic == *r) {
2586 return Some(tcx.lifetimes.re_static);
2589 // Determine whether there is exactly one unique region in the set
2590 // of derived region bounds. If so, use that. Otherwise, report an
2592 let r = derived_region_bounds[0];
2593 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2594 tcx.sess.emit_err(AmbiguousLifetimeBound { span });
2599 fn maybe_lint_bare_trait(&self, self_ty: &hir::Ty<'_>, in_path: bool) {
2600 let tcx = self.tcx();
2601 if let hir::TyKind::TraitObject([poly_trait_ref, ..], _, TraitObjectSyntax::None) =
2604 let needs_bracket = in_path
2608 .span_to_prev_source(self_ty.span)
2610 .map_or(false, |s| s.trim_end().ends_with('<'));
2612 let is_global = poly_trait_ref.trait_ref.path.is_global();
2613 let sugg = Vec::from_iter([
2615 self_ty.span.shrink_to_lo(),
2618 if needs_bracket { "<" } else { "" },
2619 if is_global { "(" } else { "" },
2623 self_ty.span.shrink_to_hi(),
2626 if is_global { ")" } else { "" },
2627 if needs_bracket { ">" } else { "" },
2631 if self_ty.span.edition() >= Edition::Edition2021 {
2632 let msg = "trait objects must include the `dyn` keyword";
2633 let label = "add `dyn` keyword before this trait";
2634 rustc_errors::struct_span_err!(tcx.sess, self_ty.span, E0782, "{}", msg)
2635 .multipart_suggestion_verbose(label, sugg, Applicability::MachineApplicable)
2638 let msg = "trait objects without an explicit `dyn` are deprecated";
2639 tcx.struct_span_lint_hir(
2645 .multipart_suggestion_verbose(
2648 Applicability::MachineApplicable,