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::HirPlaceholderCollector;
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};
19 struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, FatalError,
23 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
24 use rustc_hir::def_id::{DefId, LocalDefId};
25 use rustc_hir::intravisit::{walk_generics, Visitor as _};
26 use rustc_hir::lang_items::LangItem;
27 use rustc_hir::{GenericArg, GenericArgs, OpaqueTyOrigin};
28 use rustc_middle::middle::stability::AllowUnstable;
29 use rustc_middle::ty::subst::{self, GenericArgKind, InternalSubsts, Subst, SubstsRef};
30 use rustc_middle::ty::GenericParamDefKind;
31 use rustc_middle::ty::{
32 self, Const, DefIdTree, EarlyBinder, IsSuggestable, Ty, TyCtxt, TypeVisitable,
34 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, BARE_TRAIT_OBJECTS};
35 use rustc_span::edition::Edition;
36 use rustc_span::lev_distance::find_best_match_for_name;
37 use rustc_span::symbol::{kw, Ident, Symbol};
38 use rustc_span::{Span, DUMMY_SP};
39 use rustc_target::spec::abi;
40 use rustc_trait_selection::traits;
41 use rustc_trait_selection::traits::astconv_object_safety_violations;
42 use rustc_trait_selection::traits::error_reporting::{
43 report_object_safety_error, suggestions::NextTypeParamName,
45 use rustc_trait_selection::traits::wf::object_region_bounds;
47 use smallvec::SmallVec;
48 use std::collections::BTreeSet;
52 pub struct PathSeg(pub DefId, pub usize);
54 pub trait AstConv<'tcx> {
55 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
57 fn item_def_id(&self) -> Option<DefId>;
59 /// Returns predicates in scope of the form `X: Foo<T>`, where `X`
60 /// is a type parameter `X` with the given id `def_id` and T
61 /// matches `assoc_name`. This is a subset of the full set of
64 /// This is used for one specific purpose: resolving "short-hand"
65 /// associated type references like `T::Item`. In principle, we
66 /// would do that by first getting the full set of predicates in
67 /// scope and then filtering down to find those that apply to `T`,
68 /// but this can lead to cycle errors. The problem is that we have
69 /// to do this resolution *in order to create the predicates in
70 /// the first place*. Hence, we have this "special pass".
71 fn get_type_parameter_bounds(
76 ) -> ty::GenericPredicates<'tcx>;
78 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
79 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
80 -> Option<ty::Region<'tcx>>;
82 /// Returns the type to use when a type is omitted.
83 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
85 /// Returns `true` if `_` is allowed in type signatures in the current context.
86 fn allow_ty_infer(&self) -> bool;
88 /// Returns the const to use when a const is omitted.
92 param: Option<&ty::GenericParamDef>,
96 /// Projecting an associated type from a (potentially)
97 /// higher-ranked trait reference is more complicated, because of
98 /// the possibility of late-bound regions appearing in the
99 /// associated type binding. This is not legal in function
100 /// signatures for that reason. In a function body, we can always
101 /// handle it because we can use inference variables to remove the
102 /// late-bound regions.
103 fn projected_ty_from_poly_trait_ref(
107 item_segment: &hir::PathSegment<'_>,
108 poly_trait_ref: ty::PolyTraitRef<'tcx>,
111 /// Normalize an associated type coming from the user.
112 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
114 /// Invoked when we encounter an error from some prior pass
115 /// (e.g., resolve) that is translated into a ty-error. This is
116 /// used to help suppress derived errors typeck might otherwise
118 fn set_tainted_by_errors(&self);
120 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
124 struct ConvertedBinding<'a, 'tcx> {
127 kind: ConvertedBindingKind<'a, 'tcx>,
128 gen_args: &'a GenericArgs<'a>,
133 enum ConvertedBindingKind<'a, 'tcx> {
134 Equality(ty::Term<'tcx>),
135 Constraint(&'a [hir::GenericBound<'a>]),
138 /// New-typed boolean indicating whether explicit late-bound lifetimes
139 /// are present in a set of generic arguments.
141 /// For example if we have some method `fn f<'a>(&'a self)` implemented
142 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
143 /// is late-bound so should not be provided explicitly. Thus, if `f` is
144 /// instantiated with some generic arguments providing `'a` explicitly,
145 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
146 /// can provide an appropriate diagnostic later.
147 #[derive(Copy, Clone, PartialEq)]
148 pub enum ExplicitLateBound {
153 #[derive(Copy, Clone, PartialEq)]
154 pub enum IsMethodCall {
159 /// Denotes the "position" of a generic argument, indicating if it is a generic type,
160 /// generic function or generic method call.
161 #[derive(Copy, Clone, PartialEq)]
162 pub(crate) enum GenericArgPosition {
164 Value, // e.g., functions
168 /// A marker denoting that the generic arguments that were
169 /// provided did not match the respective generic parameters.
170 #[derive(Clone, Default)]
171 pub struct GenericArgCountMismatch {
172 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
173 pub reported: Option<ErrorGuaranteed>,
174 /// A list of spans of arguments provided that were not valid.
175 pub invalid_args: Vec<Span>,
178 /// Decorates the result of a generic argument count mismatch
179 /// check with whether explicit late bounds were provided.
181 pub struct GenericArgCountResult {
182 pub explicit_late_bound: ExplicitLateBound,
183 pub correct: Result<(), GenericArgCountMismatch>,
186 pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> {
187 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
191 param: &ty::GenericParamDef,
192 arg: &GenericArg<'_>,
193 ) -> subst::GenericArg<'tcx>;
197 substs: Option<&[subst::GenericArg<'tcx>]>,
198 param: &ty::GenericParamDef,
200 ) -> subst::GenericArg<'tcx>;
203 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
204 #[tracing::instrument(level = "debug", skip(self))]
205 pub fn ast_region_to_region(
207 lifetime: &hir::Lifetime,
208 def: Option<&ty::GenericParamDef>,
209 ) -> ty::Region<'tcx> {
210 let tcx = self.tcx();
211 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
213 let r = match tcx.named_region(lifetime.hir_id) {
214 Some(rl::Region::Static) => tcx.lifetimes.re_static,
216 Some(rl::Region::LateBound(debruijn, index, def_id)) => {
217 let name = lifetime_name(def_id.expect_local());
218 let br = ty::BoundRegion {
219 var: ty::BoundVar::from_u32(index),
220 kind: ty::BrNamed(def_id, name),
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 /// Constraints on associated types are created from `create_assoc_bindings_for_generic_args`.
295 /// ```ignore (illustrative)
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 from `create_assoc_bindings_for_generic_args`.
307 /// Note that the type listing given here is *exactly* what the user provided.
309 /// For (generic) associated types
311 /// ```ignore (illustrative)
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<Symbol>,
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().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(
429 // Default generic parameters may not be marked
430 // with stability attributes, i.e. when the
431 // default parameter was defined at the same time
432 // as the rest of the type. As such, we ignore missing
433 // stability attributes.
437 if let (hir::TyKind::Infer, false) = (&ty.kind, self.astconv.allow_ty_infer()) {
438 self.inferred_params.push(ty.span);
439 tcx.ty_error().into()
441 self.astconv.ast_ty_to_ty(ty).into()
445 match (¶m.kind, arg) {
446 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
447 self.astconv.ast_region_to_region(lt, Some(param)).into()
449 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
450 handle_ty_args(has_default, ty)
452 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
453 handle_ty_args(has_default, &inf.to_ty())
455 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
456 ty::Const::from_opt_const_arg_anon_const(
458 ty::WithOptConstParam {
459 did: tcx.hir().local_def_id(ct.value.hir_id),
460 const_param_did: Some(param.def_id),
465 (&GenericParamDefKind::Const { .. }, hir::GenericArg::Infer(inf)) => {
466 let ty = tcx.at(self.span).type_of(param.def_id);
467 if self.astconv.allow_ty_infer() {
468 self.astconv.ct_infer(ty, Some(param), inf.span).into()
470 self.inferred_params.push(inf.span);
471 tcx.const_error(ty).into()
480 substs: Option<&[subst::GenericArg<'tcx>]>,
481 param: &ty::GenericParamDef,
483 ) -> subst::GenericArg<'tcx> {
484 let tcx = self.astconv.tcx();
486 GenericParamDefKind::Lifetime => self
488 .re_infer(Some(param), self.span)
490 debug!(?param, "unelided lifetime in signature");
492 // This indicates an illegal lifetime in a non-assoc-trait position
493 tcx.sess.delay_span_bug(self.span, "unelided lifetime in signature");
495 // Supply some dummy value. We don't have an
496 // `re_error`, annoyingly, so use `'static`.
497 tcx.lifetimes.re_static
500 GenericParamDefKind::Type { has_default, .. } => {
501 if !infer_args && has_default {
502 // No type parameter provided, but a default exists.
504 // If we are converting an object type, then the
505 // `Self` parameter is unknown. However, some of the
506 // other type parameters may reference `Self` in their
507 // defaults. This will lead to an ICE if we are not
509 if self.default_needs_object_self(param) {
510 self.missing_type_params.push(param.name);
511 tcx.ty_error().into()
513 // This is a default type parameter.
514 let substs = substs.unwrap();
515 if substs.iter().any(|arg| match arg.unpack() {
516 GenericArgKind::Type(ty) => ty.references_error(),
519 // Avoid ICE #86756 when type error recovery goes awry.
520 return tcx.ty_error().into();
525 EarlyBinder(tcx.at(self.span).type_of(param.def_id))
530 } else if infer_args {
531 // No type parameters were provided, we can infer all.
532 let param = if !self.default_needs_object_self(param) {
537 self.astconv.ty_infer(param, self.span).into()
539 // We've already errored above about the mismatch.
540 tcx.ty_error().into()
543 GenericParamDefKind::Const { has_default } => {
544 let ty = tcx.at(self.span).type_of(param.def_id);
545 if !infer_args && has_default {
546 tcx.bound_const_param_default(param.def_id)
547 .subst(tcx, substs.unwrap())
551 self.astconv.ct_infer(ty, Some(param), self.span).into()
553 // We've already errored above about the mismatch.
554 tcx.const_error(ty).into()
562 let mut substs_ctx = SubstsForAstPathCtxt {
567 missing_type_params: vec![],
568 inferred_params: vec![],
572 let substs = Self::create_substs_for_generic_args(
582 self.complain_about_missing_type_params(
583 substs_ctx.missing_type_params,
586 generic_args.args.is_empty(),
590 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
591 generics, self_ty, substs
597 fn create_assoc_bindings_for_generic_args<'a>(
599 generic_args: &'a hir::GenericArgs<'_>,
600 ) -> Vec<ConvertedBinding<'a, 'tcx>> {
601 // Convert associated-type bindings or constraints into a separate vector.
602 // Example: Given this:
604 // T: Iterator<Item = u32>
606 // The `T` is passed in as a self-type; the `Item = u32` is
607 // not a "type parameter" of the `Iterator` trait, but rather
608 // a restriction on `<T as Iterator>::Item`, so it is passed
610 let assoc_bindings = generic_args
614 let kind = match binding.kind {
615 hir::TypeBindingKind::Equality { ref term } => match term {
616 hir::Term::Ty(ref ty) => {
617 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty).into())
619 hir::Term::Const(ref c) => {
620 let local_did = self.tcx().hir().local_def_id(c.hir_id);
621 let c = Const::from_anon_const(self.tcx(), local_did);
622 ConvertedBindingKind::Equality(c.into())
625 hir::TypeBindingKind::Constraint { ref bounds } => {
626 ConvertedBindingKind::Constraint(bounds)
630 hir_id: binding.hir_id,
631 item_name: binding.ident,
633 gen_args: binding.gen_args,
642 pub(crate) fn create_substs_for_associated_item(
647 item_segment: &hir::PathSegment<'_>,
648 parent_substs: SubstsRef<'tcx>,
649 ) -> SubstsRef<'tcx> {
651 "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}",
652 span, item_def_id, item_segment
654 if tcx.generics_of(item_def_id).params.is_empty() {
655 self.prohibit_generics(slice::from_ref(item_segment).iter(), |_| {});
659 self.create_substs_for_ast_path(
665 item_segment.infer_args,
672 /// Instantiates the path for the given trait reference, assuming that it's
673 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
674 /// The type _cannot_ be a type other than a trait type.
676 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
677 /// are disallowed. Otherwise, they are pushed onto the vector given.
678 pub fn instantiate_mono_trait_ref(
680 trait_ref: &hir::TraitRef<'_>,
682 ) -> ty::TraitRef<'tcx> {
683 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
685 self.ast_path_to_mono_trait_ref(
687 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
689 trait_ref.path.segments.last().unwrap(),
694 fn instantiate_poly_trait_ref_inner(
698 binding_span: Option<Span>,
699 constness: ty::BoundConstness,
700 bounds: &mut Bounds<'tcx>,
702 trait_ref_span: Span,
704 trait_segment: &hir::PathSegment<'_>,
705 args: &GenericArgs<'_>,
708 ) -> GenericArgCountResult {
709 let (substs, arg_count) = self.create_substs_for_ast_path(
719 let tcx = self.tcx();
720 let bound_vars = tcx.late_bound_vars(hir_id);
723 let assoc_bindings = self.create_assoc_bindings_for_generic_args(args);
726 ty::Binder::bind_with_vars(ty::TraitRef::new(trait_def_id, substs), bound_vars);
728 debug!(?poly_trait_ref, ?assoc_bindings);
729 bounds.trait_bounds.push((poly_trait_ref, span, constness));
731 let mut dup_bindings = FxHashMap::default();
732 for binding in &assoc_bindings {
733 // Specify type to assert that error was already reported in `Err` case.
734 let _: Result<_, ErrorGuaranteed> = self.add_predicates_for_ast_type_binding(
741 binding_span.unwrap_or(binding.span),
743 // Okay to ignore `Err` because of `ErrorGuaranteed` (see above).
749 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
750 /// a full trait reference. The resulting trait reference is returned. This may also generate
751 /// auxiliary bounds, which are added to `bounds`.
755 /// ```ignore (illustrative)
756 /// poly_trait_ref = Iterator<Item = u32>
760 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
762 /// **A note on binders:** against our usual convention, there is an implied bounder around
763 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
764 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
765 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
766 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
768 #[tracing::instrument(level = "debug", skip(self, span, constness, bounds, speculative))]
769 pub(crate) fn instantiate_poly_trait_ref(
771 trait_ref: &hir::TraitRef<'_>,
773 constness: ty::BoundConstness,
775 bounds: &mut Bounds<'tcx>,
777 ) -> GenericArgCountResult {
778 let hir_id = trait_ref.hir_ref_id;
779 let binding_span = None;
780 let trait_ref_span = trait_ref.path.span;
781 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
782 let trait_segment = trait_ref.path.segments.last().unwrap();
783 let args = trait_segment.args();
784 let infer_args = trait_segment.infer_args;
786 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
787 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, false);
789 self.instantiate_poly_trait_ref_inner(
805 pub(crate) fn instantiate_lang_item_trait_ref(
807 lang_item: hir::LangItem,
810 args: &GenericArgs<'_>,
812 bounds: &mut Bounds<'tcx>,
814 let binding_span = Some(span);
815 let constness = ty::BoundConstness::NotConst;
816 let speculative = false;
817 let trait_ref_span = span;
818 let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
819 let trait_segment = &hir::PathSegment::invalid();
820 let infer_args = false;
822 self.instantiate_poly_trait_ref_inner(
838 fn ast_path_to_mono_trait_ref(
843 trait_segment: &hir::PathSegment<'_>,
845 ) -> ty::TraitRef<'tcx> {
846 let (substs, _) = self.create_substs_for_ast_trait_ref(
853 let assoc_bindings = self.create_assoc_bindings_for_generic_args(trait_segment.args());
854 if let Some(b) = assoc_bindings.first() {
855 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
857 ty::TraitRef::new(trait_def_id, substs)
860 #[tracing::instrument(level = "debug", skip(self, span))]
861 fn create_substs_for_ast_trait_ref<'a>(
866 trait_segment: &'a hir::PathSegment<'a>,
868 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
869 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
871 self.create_substs_for_ast_path(
876 trait_segment.args(),
877 trait_segment.infer_args,
882 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
884 .associated_items(trait_def_id)
885 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
888 fn trait_defines_associated_const_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
890 .associated_items(trait_def_id)
891 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Const, trait_def_id)
895 // Sets `implicitly_sized` to true on `Bounds` if necessary
896 pub(crate) fn add_implicitly_sized<'hir>(
898 bounds: &mut Bounds<'hir>,
899 ast_bounds: &'hir [hir::GenericBound<'hir>],
900 self_ty_where_predicates: Option<(hir::HirId, &'hir [hir::WherePredicate<'hir>])>,
903 let tcx = self.tcx();
905 // Try to find an unbound in bounds.
906 let mut unbound = None;
907 let mut search_bounds = |ast_bounds: &'hir [hir::GenericBound<'hir>]| {
908 for ab in ast_bounds {
909 if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab {
910 if unbound.is_none() {
911 unbound = Some(&ptr.trait_ref);
913 tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span });
918 search_bounds(ast_bounds);
919 if let Some((self_ty, where_clause)) = self_ty_where_predicates {
920 let self_ty_def_id = tcx.hir().local_def_id(self_ty).to_def_id();
921 for clause in where_clause {
922 if let hir::WherePredicate::BoundPredicate(pred) = clause {
923 if pred.is_param_bound(self_ty_def_id) {
924 search_bounds(pred.bounds);
930 let sized_def_id = tcx.lang_items().require(LangItem::Sized);
931 match (&sized_def_id, unbound) {
932 (Ok(sized_def_id), Some(tpb))
933 if tpb.path.res == Res::Def(DefKind::Trait, *sized_def_id) =>
935 // There was in fact a `?Sized` bound, return without doing anything
939 // There was a `?Trait` bound, but it was not `?Sized`; warn.
942 "default bound relaxed for a type parameter, but \
943 this does nothing because the given bound is not \
944 a default; only `?Sized` is supported",
946 // Otherwise, add implicitly sized if `Sized` is available.
949 // There was no `?Sized` bound; add implicitly sized if `Sized` is available.
952 if sized_def_id.is_err() {
953 // No lang item for `Sized`, so we can't add it as a bound.
956 bounds.implicitly_sized = Some(span);
959 /// This helper takes a *converted* parameter type (`param_ty`)
960 /// and an *unconverted* list of bounds:
964 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
966 /// `param_ty`, in ty form
969 /// It adds these `ast_bounds` into the `bounds` structure.
971 /// **A note on binders:** there is an implied binder around
972 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
973 /// for more details.
974 #[tracing::instrument(level = "debug", skip(self, ast_bounds, bounds))]
975 pub(crate) fn add_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'hir>>>(
979 bounds: &mut Bounds<'tcx>,
980 bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
982 for ast_bound in ast_bounds {
984 hir::GenericBound::Trait(poly_trait_ref, modifier) => {
985 let constness = match modifier {
986 hir::TraitBoundModifier::MaybeConst => ty::BoundConstness::ConstIfConst,
987 hir::TraitBoundModifier::None => ty::BoundConstness::NotConst,
988 hir::TraitBoundModifier::Maybe => continue,
991 let _ = self.instantiate_poly_trait_ref(
992 &poly_trait_ref.trait_ref,
1000 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
1001 self.instantiate_lang_item_trait_ref(
1002 lang_item, span, hir_id, args, param_ty, bounds,
1005 hir::GenericBound::Outlives(lifetime) => {
1006 let region = self.ast_region_to_region(lifetime, None);
1009 .push((ty::Binder::bind_with_vars(region, bound_vars), lifetime.span));
1015 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1016 /// The self-type for the bounds is given by `param_ty`.
1020 /// ```ignore (illustrative)
1021 /// fn foo<T: Bar + Baz>() { }
1022 /// // ^ ^^^^^^^^^ ast_bounds
1026 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1027 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1028 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1030 /// `span` should be the declaration size of the parameter.
1031 pub(crate) fn compute_bounds(
1034 ast_bounds: &[hir::GenericBound<'_>],
1036 self.compute_bounds_inner(param_ty, ast_bounds)
1039 /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type
1040 /// named `assoc_name` into ty::Bounds. Ignore the rest.
1041 pub(crate) fn compute_bounds_that_match_assoc_type(
1044 ast_bounds: &[hir::GenericBound<'_>],
1047 let mut result = Vec::new();
1049 for ast_bound in ast_bounds {
1050 if let Some(trait_ref) = ast_bound.trait_ref()
1051 && let Some(trait_did) = trait_ref.trait_def_id()
1052 && self.tcx().trait_may_define_assoc_type(trait_did, assoc_name)
1054 result.push(ast_bound.clone());
1058 self.compute_bounds_inner(param_ty, &result)
1061 fn compute_bounds_inner(
1064 ast_bounds: &[hir::GenericBound<'_>],
1066 let mut bounds = Bounds::default();
1068 self.add_bounds(param_ty, ast_bounds.iter(), &mut bounds, ty::List::empty());
1074 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1077 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1078 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1079 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1080 #[tracing::instrument(
1082 skip(self, bounds, speculative, dup_bindings, path_span)
1084 fn add_predicates_for_ast_type_binding(
1086 hir_ref_id: hir::HirId,
1087 trait_ref: ty::PolyTraitRef<'tcx>,
1088 binding: &ConvertedBinding<'_, 'tcx>,
1089 bounds: &mut Bounds<'tcx>,
1091 dup_bindings: &mut FxHashMap<DefId, Span>,
1093 ) -> Result<(), ErrorGuaranteed> {
1094 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1095 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1096 // subtle in the event that `T` is defined in a supertrait of
1097 // `SomeTrait`, because in that case we need to upcast.
1099 // That is, consider this case:
1102 // trait SubTrait: SuperTrait<i32> { }
1103 // trait SuperTrait<A> { type T; }
1105 // ... B: SubTrait<T = foo> ...
1108 // We want to produce `<B as SuperTrait<i32>>::T == foo`.
1110 let tcx = self.tcx();
1113 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1114 // Simple case: X is defined in the current trait.
1117 // Otherwise, we have to walk through the supertraits to find
1119 self.one_bound_for_assoc_type(
1120 || traits::supertraits(tcx, trait_ref),
1121 || trait_ref.print_only_trait_path().to_string(),
1124 || match binding.kind {
1125 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1131 let (assoc_ident, def_scope) =
1132 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1134 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1135 // of calling `filter_by_name_and_kind`.
1136 let find_item_of_kind = |kind| {
1137 tcx.associated_items(candidate.def_id())
1138 .filter_by_name_unhygienic(assoc_ident.name)
1139 .find(|i| i.kind == kind && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident)
1141 let assoc_item = find_item_of_kind(ty::AssocKind::Type)
1142 .or_else(|| find_item_of_kind(ty::AssocKind::Const))
1143 .expect("missing associated type");
1145 if !assoc_item.visibility(tcx).is_accessible_from(def_scope, tcx) {
1149 &format!("{} `{}` is private", assoc_item.kind, binding.item_name),
1151 .span_label(binding.span, &format!("private {}", assoc_item.kind))
1154 tcx.check_stability(assoc_item.def_id, Some(hir_ref_id), binding.span, None);
1158 .entry(assoc_item.def_id)
1159 .and_modify(|prev_span| {
1160 self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified {
1162 prev_span: *prev_span,
1163 item_name: binding.item_name,
1164 def_path: tcx.def_path_str(assoc_item.container_id(tcx)),
1167 .or_insert(binding.span);
1170 // Include substitutions for generic parameters of associated types
1171 let projection_ty = candidate.map_bound(|trait_ref| {
1172 let ident = Ident::new(assoc_item.name, binding.item_name.span);
1173 let item_segment = hir::PathSegment {
1175 hir_id: Some(binding.hir_id),
1177 args: Some(binding.gen_args),
1181 let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item(
1190 "add_predicates_for_ast_type_binding: substs for trait-ref and assoc_item: {:?}",
1191 substs_trait_ref_and_assoc_item
1195 item_def_id: assoc_item.def_id,
1196 substs: substs_trait_ref_and_assoc_item,
1201 // Find any late-bound regions declared in `ty` that are not
1202 // declared in the trait-ref or assoc_item. These are not well-formed.
1206 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1207 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1208 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1209 let late_bound_in_trait_ref =
1210 tcx.collect_constrained_late_bound_regions(&projection_ty);
1211 let late_bound_in_ty =
1212 tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty));
1213 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1214 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1216 // FIXME: point at the type params that don't have appropriate lifetimes:
1217 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1218 // ---- ---- ^^^^^^^
1219 self.validate_late_bound_regions(
1220 late_bound_in_trait_ref,
1227 "binding for associated type `{}` references {}, \
1228 which does not appear in the trait input types",
1237 match binding.kind {
1238 ConvertedBindingKind::Equality(mut term) => {
1239 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1240 // the "projection predicate" for:
1242 // `<T as Iterator>::Item = u32`
1243 let assoc_item_def_id = projection_ty.skip_binder().item_def_id;
1244 let def_kind = tcx.def_kind(assoc_item_def_id);
1245 match (def_kind, term) {
1246 (hir::def::DefKind::AssocTy, ty::Term::Ty(_))
1247 | (hir::def::DefKind::AssocConst, ty::Term::Const(_)) => (),
1249 let got = if let ty::Term::Ty(_) = term { "type" } else { "constant" };
1250 let expected = def_kind.descr(assoc_item_def_id);
1254 &format!("expected {expected} bound, found {got}"),
1257 tcx.def_span(assoc_item_def_id),
1258 &format!("{expected} defined here"),
1261 term = match def_kind {
1262 hir::def::DefKind::AssocTy => tcx.ty_error().into(),
1263 hir::def::DefKind::AssocConst => tcx
1265 tcx.bound_type_of(assoc_item_def_id)
1266 .subst(tcx, projection_ty.skip_binder().substs),
1269 _ => unreachable!(),
1273 bounds.projection_bounds.push((
1274 projection_ty.map_bound(|projection_ty| ty::ProjectionPredicate {
1281 ConvertedBindingKind::Constraint(ast_bounds) => {
1282 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1284 // `<T as Iterator>::Item: Debug`
1286 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1287 // parameter to have a skipped binder.
1288 let param_ty = tcx.mk_ty(ty::Projection(projection_ty.skip_binder()));
1289 self.add_bounds(param_ty, ast_bounds.iter(), bounds, candidate.bound_vars());
1299 item_segment: &hir::PathSegment<'_>,
1301 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1304 EarlyBinder(self.tcx().at(span).type_of(did)).subst(self.tcx(), substs),
1308 fn conv_object_ty_poly_trait_ref(
1311 trait_bounds: &[hir::PolyTraitRef<'_>],
1312 lifetime: &hir::Lifetime,
1315 let tcx = self.tcx();
1317 let mut bounds = Bounds::default();
1318 let mut potential_assoc_types = Vec::new();
1319 let dummy_self = self.tcx().types.trait_object_dummy_self;
1320 for trait_bound in trait_bounds.iter().rev() {
1321 if let GenericArgCountResult {
1323 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1325 } = self.instantiate_poly_trait_ref(
1326 &trait_bound.trait_ref,
1328 ty::BoundConstness::NotConst,
1333 potential_assoc_types.extend(cur_potential_assoc_types);
1337 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1338 // is used and no 'maybe' bounds are used.
1339 let expanded_traits =
1340 traits::expand_trait_aliases(tcx, bounds.trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1341 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) = expanded_traits
1342 .filter(|i| i.trait_ref().self_ty().skip_binder() == dummy_self)
1343 .partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1344 if regular_traits.len() > 1 {
1345 let first_trait = ®ular_traits[0];
1346 let additional_trait = ®ular_traits[1];
1347 let mut err = struct_span_err!(
1349 additional_trait.bottom().1,
1351 "only auto traits can be used as additional traits in a trait object"
1353 additional_trait.label_with_exp_info(
1355 "additional non-auto trait",
1358 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1360 "consider creating a new trait with all of these as supertraits and using that \
1361 trait here instead: `trait NewTrait: {} {{}}`",
1364 .map(|t| t.trait_ref().print_only_trait_path().to_string())
1365 .collect::<Vec<_>>()
1369 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1370 for more information on them, visit \
1371 <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1376 if regular_traits.is_empty() && auto_traits.is_empty() {
1377 let trait_alias_span = bounds
1380 .map(|&(trait_ref, _, _)| trait_ref.def_id())
1381 .find(|&trait_ref| tcx.is_trait_alias(trait_ref))
1382 .map(|trait_ref| tcx.def_span(trait_ref));
1383 tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span, trait_alias_span });
1384 return tcx.ty_error();
1387 // Check that there are no gross object safety violations;
1388 // most importantly, that the supertraits don't contain `Self`,
1390 for item in ®ular_traits {
1391 let object_safety_violations =
1392 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1393 if !object_safety_violations.is_empty() {
1394 report_object_safety_error(
1397 item.trait_ref().def_id(),
1398 &object_safety_violations,
1401 return tcx.ty_error();
1405 // Use a `BTreeSet` to keep output in a more consistent order.
1406 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1408 let regular_traits_refs_spans = bounds
1411 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1413 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1414 assert_eq!(constness, ty::BoundConstness::NotConst);
1416 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1418 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1419 obligation.predicate
1422 let bound_predicate = obligation.predicate.kind();
1423 match bound_predicate.skip_binder() {
1424 ty::PredicateKind::Trait(pred) => {
1425 let pred = bound_predicate.rebind(pred);
1426 associated_types.entry(span).or_default().extend(
1427 tcx.associated_items(pred.def_id())
1428 .in_definition_order()
1429 .filter(|item| item.kind == ty::AssocKind::Type)
1430 .map(|item| item.def_id),
1433 ty::PredicateKind::Projection(pred) => {
1434 let pred = bound_predicate.rebind(pred);
1435 // A `Self` within the original bound will be substituted with a
1436 // `trait_object_dummy_self`, so check for that.
1437 let references_self = match pred.skip_binder().term {
1438 ty::Term::Ty(ty) => ty.walk().any(|arg| arg == dummy_self.into()),
1439 ty::Term::Const(c) => c.ty().walk().any(|arg| arg == dummy_self.into()),
1442 // If the projection output contains `Self`, force the user to
1443 // elaborate it explicitly to avoid a lot of complexity.
1445 // The "classically useful" case is the following:
1447 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1452 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1453 // but actually supporting that would "expand" to an infinitely-long type
1454 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1456 // Instead, we force the user to write
1457 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1458 // the discussion in #56288 for alternatives.
1459 if !references_self {
1460 // Include projections defined on supertraits.
1461 bounds.projection_bounds.push((pred, span));
1469 for (projection_bound, _) in &bounds.projection_bounds {
1470 for def_ids in associated_types.values_mut() {
1471 def_ids.remove(&projection_bound.projection_def_id());
1475 self.complain_about_missing_associated_types(
1477 potential_assoc_types,
1481 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1482 // `dyn Trait + Send`.
1483 // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering
1485 let mut duplicates = FxHashSet::default();
1486 auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id()));
1487 debug!("regular_traits: {:?}", regular_traits);
1488 debug!("auto_traits: {:?}", auto_traits);
1490 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1491 let existential_trait_refs = regular_traits.iter().map(|i| {
1492 i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| {
1493 if trait_ref.self_ty() != dummy_self {
1494 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1495 // which picks up non-supertraits where clauses - but also, the object safety
1496 // completely ignores trait aliases, which could be object safety hazards. We
1497 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1498 // disabled. (#66420)
1499 tcx.sess.delay_span_bug(
1502 "trait_ref_to_existential called on {:?} with non-dummy Self",
1507 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1510 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1511 bound.map_bound(|b| {
1512 if b.projection_ty.self_ty() != dummy_self {
1513 tcx.sess.delay_span_bug(
1515 &format!("trait_ref_to_existential called on {:?} with non-dummy Self", b),
1518 ty::ExistentialProjection::erase_self_ty(tcx, b)
1522 let regular_trait_predicates = existential_trait_refs
1523 .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait));
1524 let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| {
1525 ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()))
1527 // N.b. principal, projections, auto traits
1528 // FIXME: This is actually wrong with multiple principals in regards to symbol mangling
1529 let mut v = regular_trait_predicates
1531 existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)),
1533 .chain(auto_trait_predicates)
1534 .collect::<SmallVec<[_; 8]>>();
1535 v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
1537 let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter());
1539 // Use explicitly-specified region bound.
1540 let region_bound = if !lifetime.is_elided() {
1541 self.ast_region_to_region(lifetime, None)
1543 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1544 if tcx.named_region(lifetime.hir_id).is_some() {
1545 self.ast_region_to_region(lifetime, None)
1547 self.re_infer(None, span).unwrap_or_else(|| {
1548 let mut err = struct_span_err!(
1552 "the lifetime bound for this object type cannot be deduced \
1553 from context; please supply an explicit bound"
1556 // We will have already emitted an error E0106 complaining about a
1557 // missing named lifetime in `&dyn Trait`, so we elide this one.
1562 tcx.lifetimes.re_static
1567 debug!("region_bound: {:?}", region_bound);
1569 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1570 debug!("trait_object_type: {:?}", ty);
1574 fn report_ambiguous_associated_type(
1580 ) -> ErrorGuaranteed {
1581 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1585 .confused_type_with_std_module
1587 .any(|full_span| full_span.contains(span))
1589 err.span_suggestion(
1590 span.shrink_to_lo(),
1591 "you are looking for the module in `std`, not the primitive type",
1593 Applicability::MachineApplicable,
1596 err.span_suggestion(
1598 "use fully-qualified syntax",
1599 format!("<{} as {}>::{}", type_str, trait_str, name),
1600 Applicability::HasPlaceholders,
1606 // Search for a bound on a type parameter which includes the associated item
1607 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1608 // This function will fail if there are no suitable bounds or there is
1610 fn find_bound_for_assoc_item(
1612 ty_param_def_id: LocalDefId,
1615 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1616 let tcx = self.tcx();
1619 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1620 ty_param_def_id, assoc_name, span,
1623 let predicates = &self
1624 .get_type_parameter_bounds(span, ty_param_def_id.to_def_id(), assoc_name)
1627 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1629 let param_name = tcx.hir().ty_param_name(ty_param_def_id);
1630 self.one_bound_for_assoc_type(
1632 traits::transitive_bounds_that_define_assoc_type(
1634 predicates.iter().filter_map(|(p, _)| {
1635 Some(p.to_opt_poly_trait_pred()?.map_bound(|t| t.trait_ref))
1640 || param_name.to_string(),
1647 // Checks that `bounds` contains exactly one element and reports appropriate
1648 // errors otherwise.
1649 fn one_bound_for_assoc_type<I>(
1651 all_candidates: impl Fn() -> I,
1652 ty_param_name: impl Fn() -> String,
1655 is_equality: impl Fn() -> Option<String>,
1656 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1658 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1660 let mut matching_candidates = all_candidates()
1661 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1662 let mut const_candidates = all_candidates()
1663 .filter(|r| self.trait_defines_associated_const_named(r.def_id(), assoc_name));
1665 let (bound, next_cand) = match (matching_candidates.next(), const_candidates.next()) {
1666 (Some(bound), _) => (bound, matching_candidates.next()),
1667 (None, Some(bound)) => (bound, const_candidates.next()),
1669 let reported = self.complain_about_assoc_type_not_found(
1675 return Err(reported);
1678 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1680 if let Some(bound2) = next_cand {
1681 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1683 let is_equality = is_equality();
1684 let bounds = IntoIterator::into_iter([bound, bound2]).chain(matching_candidates);
1685 let mut err = if is_equality.is_some() {
1686 // More specific Error Index entry.
1691 "ambiguous associated type `{}` in bounds of `{}`",
1700 "ambiguous associated type `{}` in bounds of `{}`",
1705 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1707 let mut where_bounds = vec![];
1708 for bound in bounds {
1709 let bound_id = bound.def_id();
1710 let bound_span = self
1712 .associated_items(bound_id)
1713 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
1714 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1716 if let Some(bound_span) = bound_span {
1720 "ambiguous `{}` from `{}`",
1722 bound.print_only_trait_path(),
1725 if let Some(constraint) = &is_equality {
1726 where_bounds.push(format!(
1727 " T: {trait}::{assoc} = {constraint}",
1728 trait=bound.print_only_trait_path(),
1730 constraint=constraint,
1733 err.span_suggestion_verbose(
1734 span.with_hi(assoc_name.span.lo()),
1735 "use fully qualified syntax to disambiguate",
1739 bound.print_only_trait_path(),
1741 Applicability::MaybeIncorrect,
1746 "associated type `{}` could derive from `{}`",
1748 bound.print_only_trait_path(),
1752 if !where_bounds.is_empty() {
1754 "consider introducing a new type parameter `T` and adding `where` constraints:\
1755 \n where\n T: {},\n{}",
1757 where_bounds.join(",\n"),
1760 let reported = err.emit();
1761 if !where_bounds.is_empty() {
1762 return Err(reported);
1769 // Create a type from a path to an associated type.
1770 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1771 // and item_segment is the path segment for `D`. We return a type and a def for
1773 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1774 // parameter or `Self`.
1775 // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1776 // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
1777 pub fn associated_path_to_ty(
1779 hir_ref_id: hir::HirId,
1782 qself: &hir::Ty<'_>,
1783 assoc_segment: &hir::PathSegment<'_>,
1784 permit_variants: bool,
1785 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1786 let tcx = self.tcx();
1787 let assoc_ident = assoc_segment.ident;
1788 let qself_res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
1794 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1796 // Check if we have an enum variant.
1797 let mut variant_resolution = None;
1798 if let ty::Adt(adt_def, _) = qself_ty.kind() {
1799 if adt_def.is_enum() {
1800 let variant_def = adt_def
1803 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident(tcx), adt_def.did()));
1804 if let Some(variant_def) = variant_def {
1805 if permit_variants {
1806 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None);
1807 self.prohibit_generics(slice::from_ref(assoc_segment).iter(), |err| {
1808 err.note("enum variants can't have type parameters");
1809 let type_name = tcx.item_name(adt_def.did());
1811 "you might have meant to specity type parameters on enum \
1814 let Some(args) = assoc_segment.args else { return; };
1815 // Get the span of the generics args *including* the leading `::`.
1816 let args_span = assoc_segment.ident.span.shrink_to_hi().to(args.span_ext);
1817 if tcx.generics_of(adt_def.did()).count() == 0 {
1818 // FIXME(estebank): we could also verify that the arguments being
1819 // work for the `enum`, instead of just looking if it takes *any*.
1820 err.span_suggestion_verbose(
1822 &format!("{type_name} doesn't have generic parameters"),
1824 Applicability::MachineApplicable,
1828 let Ok(snippet) = tcx.sess.source_map().span_to_snippet(args_span) else {
1832 let (qself_sugg_span, is_self) = if let hir::TyKind::Path(
1833 hir::QPath::Resolved(_, ref path)
1835 // If the path segment already has type params, we want to overwrite
1837 match &path.segments[..] {
1838 // `segment` is the previous to last element on the path,
1839 // which would normally be the `enum` itself, while the last
1840 // `_` `PathSegment` corresponds to the variant.
1841 [.., hir::PathSegment {
1844 res: Some(Res::Def(DefKind::Enum, _)),
1847 // We need to include the `::` in `Type::Variant::<Args>`
1848 // to point the span to `::<Args>`, not just `<Args>`.
1849 ident.span.shrink_to_hi().to(args.map_or(
1850 ident.span.shrink_to_hi(),
1855 // We need to include the `::` in `Type::Variant::<Args>`
1856 // to point the span to `::<Args>`, not just `<Args>`.
1857 segment.ident.span.shrink_to_hi().to(segment.args.map_or(
1858 segment.ident.span.shrink_to_hi(),
1860 kw::SelfUpper == segment.ident.name,
1871 let suggestion = vec![
1873 // Account for people writing `Self::Variant::<Args>`, where
1874 // `Self` is the enum, and suggest replacing `Self` with the
1875 // appropriate type: `Type::<Args>::Variant`.
1876 (qself.span, format!("{type_name}{snippet}"))
1878 (qself_sugg_span, snippet)
1880 (args_span, String::new()),
1882 err.multipart_suggestion_verbose(
1885 Applicability::MaybeIncorrect,
1888 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1890 variant_resolution = Some(variant_def.def_id);
1896 // Find the type of the associated item, and the trait where the associated
1897 // item is declared.
1898 let bound = match (&qself_ty.kind(), qself_res) {
1899 (_, Res::SelfTy { trait_: Some(_), alias_to: Some((impl_def_id, _)) }) => {
1900 // `Self` in an impl of a trait -- we have a concrete self type and a
1902 let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) else {
1903 // A cycle error occurred, most likely.
1904 let guar = tcx.sess.delay_span_bug(span, "expected cycle error");
1908 self.one_bound_for_assoc_type(
1909 || traits::supertraits(tcx, ty::Binder::dummy(trait_ref)),
1910 || "Self".to_string(),
1918 Res::SelfTy { trait_: Some(param_did), alias_to: None }
1919 | Res::Def(DefKind::TyParam, param_did),
1920 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
1922 let reported = if variant_resolution.is_some() {
1923 // Variant in type position
1924 let msg = format!("expected type, found variant `{}`", assoc_ident);
1925 tcx.sess.span_err(span, &msg)
1926 } else if qself_ty.is_enum() {
1927 let mut err = struct_span_err!(
1931 "no variant named `{}` found for enum `{}`",
1936 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1937 if let Some(suggested_name) = find_best_match_for_name(
1941 .map(|variant| variant.name)
1942 .collect::<Vec<Symbol>>(),
1946 err.span_suggestion(
1948 "there is a variant with a similar name",
1950 Applicability::MaybeIncorrect,
1955 format!("variant not found in `{}`", qself_ty),
1959 if let Some(sp) = tcx.hir().span_if_local(adt_def.did()) {
1960 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1964 } else if let Some(reported) = qself_ty.error_reported() {
1967 // Don't print `TyErr` to the user.
1968 self.report_ambiguous_associated_type(
1970 &qself_ty.to_string(),
1975 return Err(reported);
1979 let trait_did = bound.def_id();
1980 let (assoc_ident, def_scope) =
1981 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1983 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1984 // of calling `filter_by_name_and_kind`.
1985 let item = tcx.associated_items(trait_did).in_definition_order().find(|i| {
1986 i.kind.namespace() == Namespace::TypeNS
1987 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1989 // Assume that if it's not matched, there must be a const defined with the same name
1990 // but it was used in a type position.
1991 let Some(item) = item else {
1992 let msg = format!("found associated const `{assoc_ident}` when type was expected");
1993 let guar = tcx.sess.struct_span_err(span, &msg).emit();
1997 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
1998 let ty = self.normalize_ty(span, ty);
2000 let kind = DefKind::AssocTy;
2001 if !item.visibility(tcx).is_accessible_from(def_scope, tcx) {
2002 let kind = kind.descr(item.def_id);
2003 let msg = format!("{} `{}` is private", kind, assoc_ident);
2005 .struct_span_err(span, &msg)
2006 .span_label(span, &format!("private {}", kind))
2009 tcx.check_stability(item.def_id, Some(hir_ref_id), span, None);
2011 if let Some(variant_def_id) = variant_resolution {
2012 tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
2013 let mut err = lint.build("ambiguous associated item");
2014 let mut could_refer_to = |kind: DefKind, def_id, also| {
2015 let note_msg = format!(
2016 "`{}` could{} refer to the {} defined here",
2021 err.span_note(tcx.def_span(def_id), ¬e_msg);
2024 could_refer_to(DefKind::Variant, variant_def_id, "");
2025 could_refer_to(kind, item.def_id, " also");
2027 err.span_suggestion(
2029 "use fully-qualified syntax",
2030 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2031 Applicability::MachineApplicable,
2037 Ok((ty, kind, item.def_id))
2043 opt_self_ty: Option<Ty<'tcx>>,
2045 trait_segment: &hir::PathSegment<'_>,
2046 item_segment: &hir::PathSegment<'_>,
2048 let tcx = self.tcx();
2050 let trait_def_id = tcx.parent(item_def_id);
2052 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2054 let Some(self_ty) = opt_self_ty else {
2055 let path_str = tcx.def_path_str(trait_def_id);
2057 let def_id = self.item_def_id();
2059 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2061 let parent_def_id = def_id
2062 .and_then(|def_id| {
2063 def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
2065 .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id());
2067 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2069 // If the trait in segment is the same as the trait defining the item,
2070 // use the `<Self as ..>` syntax in the error.
2071 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
2072 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2074 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2080 self.report_ambiguous_associated_type(
2084 item_segment.ident.name,
2086 return tcx.ty_error();
2089 debug!("qpath_to_ty: self_type={:?}", self_ty);
2092 self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment, false);
2094 let item_substs = self.create_substs_for_associated_item(
2102 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2104 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2107 pub fn prohibit_generics<'a>(
2109 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
2110 extend: impl Fn(&mut Diagnostic),
2112 let args = segments.clone().flat_map(|segment| segment.args().args);
2114 let (lt, ty, ct, inf) =
2115 args.clone().fold((false, false, false, false), |(lt, ty, ct, inf), arg| match arg {
2116 hir::GenericArg::Lifetime(_) => (true, ty, ct, inf),
2117 hir::GenericArg::Type(_) => (lt, true, ct, inf),
2118 hir::GenericArg::Const(_) => (lt, ty, true, inf),
2119 hir::GenericArg::Infer(_) => (lt, ty, ct, true),
2121 let mut emitted = false;
2122 if lt || ty || ct || inf {
2123 let types_and_spans: Vec<_> = segments
2125 .flat_map(|segment| {
2126 segment.res.and_then(|res| {
2127 if segment.args().args.is_empty() {
2132 Res::PrimTy(ty) => format!("{} `{}`", res.descr(), ty.name()),
2134 if let Some(name) = self.tcx().opt_item_name(def_id) => {
2135 format!("{} `{name}`", res.descr())
2137 Res::Err => "this type".to_string(),
2138 _ => res.descr().to_string(),
2146 let this_type = match &types_and_spans[..] {
2147 [.., _, (last, _)] => format!(
2149 types_and_spans[..types_and_spans.len() - 1]
2151 .map(|(x, _)| x.as_str())
2153 .collect::<String>()
2155 [(only, _)] => only.to_string(),
2156 [] => "this type".to_string(),
2159 let arg_spans: Vec<Span> = args.map(|arg| arg.span()).collect();
2161 let mut kinds = Vec::with_capacity(4);
2163 kinds.push("lifetime");
2169 kinds.push("const");
2172 kinds.push("generic");
2174 let (kind, s) = match kinds[..] {
2178 kinds[..kinds.len() - 1]
2182 .collect::<String>()
2186 [only] => (format!("{only}"), ""),
2187 [] => unreachable!(),
2189 let last_span = *arg_spans.last().unwrap();
2190 let span: MultiSpan = arg_spans.into();
2191 let mut err = struct_span_err!(
2195 "{kind} arguments are not allowed on {this_type}",
2197 err.span_label(last_span, format!("{kind} argument{s} not allowed"));
2198 for (what, span) in types_and_spans {
2199 err.span_label(span, format!("not allowed on {what}"));
2206 for segment in segments {
2207 // Only emit the first error to avoid overloading the user with error messages.
2208 if let [binding, ..] = segment.args().bindings {
2209 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2216 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2217 pub fn def_ids_for_value_path_segments(
2219 segments: &[hir::PathSegment<'_>],
2220 self_ty: Option<Ty<'tcx>>,
2224 // We need to extract the type parameters supplied by the user in
2225 // the path `path`. Due to the current setup, this is a bit of a
2226 // tricky-process; the problem is that resolve only tells us the
2227 // end-point of the path resolution, and not the intermediate steps.
2228 // Luckily, we can (at least for now) deduce the intermediate steps
2229 // just from the end-point.
2231 // There are basically five cases to consider:
2233 // 1. Reference to a constructor of a struct:
2235 // struct Foo<T>(...)
2237 // In this case, the parameters are declared in the type space.
2239 // 2. Reference to a constructor of an enum variant:
2241 // enum E<T> { Foo(...) }
2243 // In this case, the parameters are defined in the type space,
2244 // but may be specified either on the type or the variant.
2246 // 3. Reference to a fn item or a free constant:
2250 // In this case, the path will again always have the form
2251 // `a::b::foo::<T>` where only the final segment should have
2252 // type parameters. However, in this case, those parameters are
2253 // declared on a value, and hence are in the `FnSpace`.
2255 // 4. Reference to a method or an associated constant:
2257 // impl<A> SomeStruct<A> {
2261 // Here we can have a path like
2262 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2263 // may appear in two places. The penultimate segment,
2264 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2265 // final segment, `foo::<B>` contains parameters in fn space.
2267 // The first step then is to categorize the segments appropriately.
2269 let tcx = self.tcx();
2271 assert!(!segments.is_empty());
2272 let last = segments.len() - 1;
2274 let mut path_segs = vec![];
2277 // Case 1. Reference to a struct constructor.
2278 DefKind::Ctor(CtorOf::Struct, ..) => {
2279 // Everything but the final segment should have no
2280 // parameters at all.
2281 let generics = tcx.generics_of(def_id);
2282 // Variant and struct constructors use the
2283 // generics of their parent type definition.
2284 let generics_def_id = generics.parent.unwrap_or(def_id);
2285 path_segs.push(PathSeg(generics_def_id, last));
2288 // Case 2. Reference to a variant constructor.
2289 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2290 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2291 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2292 debug_assert!(adt_def.is_enum());
2293 (adt_def.did(), last)
2294 } else if last >= 1 && segments[last - 1].args.is_some() {
2295 // Everything but the penultimate segment should have no
2296 // parameters at all.
2297 let mut def_id = def_id;
2299 // `DefKind::Ctor` -> `DefKind::Variant`
2300 if let DefKind::Ctor(..) = kind {
2301 def_id = tcx.parent(def_id);
2304 // `DefKind::Variant` -> `DefKind::Enum`
2305 let enum_def_id = tcx.parent(def_id);
2306 (enum_def_id, last - 1)
2308 // FIXME: lint here recommending `Enum::<...>::Variant` form
2309 // instead of `Enum::Variant::<...>` form.
2311 // Everything but the final segment should have no
2312 // parameters at all.
2313 let generics = tcx.generics_of(def_id);
2314 // Variant and struct constructors use the
2315 // generics of their parent type definition.
2316 (generics.parent.unwrap_or(def_id), last)
2318 path_segs.push(PathSeg(generics_def_id, index));
2321 // Case 3. Reference to a top-level value.
2322 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static(_) => {
2323 path_segs.push(PathSeg(def_id, last));
2326 // Case 4. Reference to a method or associated const.
2327 DefKind::AssocFn | DefKind::AssocConst => {
2328 if segments.len() >= 2 {
2329 let generics = tcx.generics_of(def_id);
2330 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2332 path_segs.push(PathSeg(def_id, last));
2335 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2338 debug!("path_segs = {:?}", path_segs);
2343 // Check a type `Path` and convert it to a `Ty`.
2346 opt_self_ty: Option<Ty<'tcx>>,
2347 path: &hir::Path<'_>,
2348 permit_variants: bool,
2350 let tcx = self.tcx();
2353 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2354 path.res, opt_self_ty, path.segments
2357 let span = path.span;
2359 Res::Def(DefKind::OpaqueTy, did) => {
2360 // Check for desugared `impl Trait`.
2361 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2362 let item_segment = path.segments.split_last().unwrap();
2363 self.prohibit_generics(item_segment.1.iter(), |err| {
2364 err.note("`impl Trait` types can't have type parameters");
2366 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2367 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2374 | DefKind::ForeignTy,
2377 assert_eq!(opt_self_ty, None);
2378 self.prohibit_generics(path.segments.split_last().unwrap().1.iter(), |_| {});
2379 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2381 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2382 // Convert "variant type" as if it were a real type.
2383 // The resulting `Ty` is type of the variant's enum for now.
2384 assert_eq!(opt_self_ty, None);
2387 self.def_ids_for_value_path_segments(path.segments, None, kind, def_id);
2388 let generic_segs: FxHashSet<_> =
2389 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2390 self.prohibit_generics(
2391 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2392 if !generic_segs.contains(&index) { Some(seg) } else { None }
2395 err.note("enum variants can't have type parameters");
2399 let PathSeg(def_id, index) = path_segs.last().unwrap();
2400 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2402 Res::Def(DefKind::TyParam, def_id) => {
2403 assert_eq!(opt_self_ty, None);
2404 self.prohibit_generics(path.segments.iter(), |err| {
2405 if let Some(span) = tcx.def_ident_span(def_id) {
2406 let name = tcx.item_name(def_id);
2407 err.span_note(span, &format!("type parameter `{name}` defined here"));
2411 let def_id = def_id.expect_local();
2412 let item_def_id = tcx.hir().ty_param_owner(def_id);
2413 let generics = tcx.generics_of(item_def_id);
2414 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2415 tcx.mk_ty_param(index, tcx.hir().ty_param_name(def_id))
2417 Res::SelfTy { trait_: Some(_), alias_to: None } => {
2418 // `Self` in trait or type alias.
2419 assert_eq!(opt_self_ty, None);
2420 self.prohibit_generics(path.segments.iter(), |err| {
2421 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments[..] {
2422 err.span_suggestion_verbose(
2423 ident.span.shrink_to_hi().to(args.span_ext),
2424 "the `Self` type doesn't accept type parameters",
2426 Applicability::MaybeIncorrect,
2430 tcx.types.self_param
2432 Res::SelfTy { trait_: _, alias_to: Some((def_id, forbid_generic)) } => {
2433 // `Self` in impl (we know the concrete type).
2434 assert_eq!(opt_self_ty, None);
2435 // Try to evaluate any array length constants.
2436 let ty = tcx.at(span).type_of(def_id);
2437 let span_of_impl = tcx.span_of_impl(def_id);
2438 self.prohibit_generics(path.segments.iter(), |err| {
2439 let def_id = match *ty.kind() {
2440 ty::Adt(self_def, _) => self_def.did(),
2444 let type_name = tcx.item_name(def_id);
2445 let span_of_ty = tcx.def_ident_span(def_id);
2446 let generics = tcx.generics_of(def_id).count();
2448 let msg = format!("`Self` is of type `{ty}`");
2449 if let (Ok(i_sp), Some(t_sp)) = (span_of_impl, span_of_ty) {
2450 let mut span: MultiSpan = vec![t_sp].into();
2451 span.push_span_label(
2453 &format!("`Self` is on type `{type_name}` in this `impl`"),
2455 let mut postfix = "";
2457 postfix = ", which doesn't have generic parameters";
2459 span.push_span_label(
2461 &format!("`Self` corresponds to this type{postfix}"),
2463 err.span_note(span, &msg);
2467 for segment in path.segments {
2468 if let Some(args) = segment.args && segment.ident.name == kw::SelfUpper {
2470 // FIXME(estebank): we could also verify that the arguments being
2471 // work for the `enum`, instead of just looking if it takes *any*.
2472 err.span_suggestion_verbose(
2473 segment.ident.span.shrink_to_hi().to(args.span_ext),
2474 "the `Self` type doesn't accept type parameters",
2476 Applicability::MachineApplicable,
2480 err.span_suggestion_verbose(
2483 "the `Self` type doesn't accept type parameters, use the \
2484 concrete type's name `{type_name}` instead if you want to \
2485 specify its type parameters"
2488 Applicability::MaybeIncorrect,
2494 // HACK(min_const_generics): Forbid generic `Self` types
2495 // here as we can't easily do that during nameres.
2497 // We do this before normalization as we otherwise allow
2499 // trait AlwaysApplicable { type Assoc; }
2500 // impl<T: ?Sized> AlwaysApplicable for T { type Assoc = usize; }
2502 // trait BindsParam<T> {
2505 // impl<T> BindsParam<T> for <T as AlwaysApplicable>::Assoc {
2506 // type ArrayTy = [u8; Self::MAX];
2509 // Note that the normalization happens in the param env of
2510 // the anon const, which is empty. This is why the
2511 // `AlwaysApplicable` impl needs a `T: ?Sized` bound for
2512 // this to compile if we were to normalize here.
2513 if forbid_generic && ty.needs_subst() {
2514 let mut err = tcx.sess.struct_span_err(
2516 "generic `Self` types are currently not permitted in anonymous constants",
2518 if let Some(hir::Node::Item(&hir::Item {
2519 kind: hir::ItemKind::Impl(ref impl_),
2521 })) = tcx.hir().get_if_local(def_id)
2523 err.span_note(impl_.self_ty.span, "not a concrete type");
2528 self.normalize_ty(span, ty)
2531 Res::Def(DefKind::AssocTy, def_id) => {
2532 debug_assert!(path.segments.len() >= 2);
2533 self.prohibit_generics(path.segments[..path.segments.len() - 2].iter(), |_| {});
2538 &path.segments[path.segments.len() - 2],
2539 path.segments.last().unwrap(),
2542 Res::PrimTy(prim_ty) => {
2543 assert_eq!(opt_self_ty, None);
2544 self.prohibit_generics(path.segments.iter(), |err| {
2545 let name = prim_ty.name_str();
2546 for segment in path.segments {
2547 if let Some(args) = segment.args {
2548 err.span_suggestion_verbose(
2549 segment.ident.span.shrink_to_hi().to(args.span_ext),
2550 &format!("primitive type `{name}` doesn't have generic parameters"),
2552 Applicability::MaybeIncorrect,
2558 hir::PrimTy::Bool => tcx.types.bool,
2559 hir::PrimTy::Char => tcx.types.char,
2560 hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2561 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2562 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2563 hir::PrimTy::Str => tcx.types.str_,
2567 self.set_tainted_by_errors();
2568 self.tcx().ty_error()
2570 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2574 /// Parses the programmer's textual representation of a type into our
2575 /// internal notion of a type.
2576 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2577 self.ast_ty_to_ty_inner(ast_ty, false, false)
2580 /// Parses the programmer's textual representation of a type into our
2581 /// internal notion of a type. This is meant to be used within a path.
2582 pub fn ast_ty_to_ty_in_path(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2583 self.ast_ty_to_ty_inner(ast_ty, false, true)
2586 /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2587 /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2588 #[tracing::instrument(level = "debug", skip(self))]
2589 fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool, in_path: bool) -> Ty<'tcx> {
2590 let tcx = self.tcx();
2592 let result_ty = match ast_ty.kind {
2593 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(ty)),
2594 hir::TyKind::Ptr(ref mt) => {
2595 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl })
2597 hir::TyKind::Rptr(ref region, ref mt) => {
2598 let r = self.ast_region_to_region(region, None);
2600 let t = self.ast_ty_to_ty_inner(mt.ty, true, false);
2601 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2603 hir::TyKind::Never => tcx.types.never,
2604 hir::TyKind::Tup(fields) => tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(t))),
2605 hir::TyKind::BareFn(bf) => {
2606 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span);
2608 tcx.mk_fn_ptr(self.ty_of_fn(
2617 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
2618 self.maybe_lint_bare_trait(ast_ty, in_path);
2619 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed)
2621 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2622 debug!(?maybe_qself, ?path);
2623 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2624 self.res_to_ty(opt_self_ty, path, false)
2626 hir::TyKind::OpaqueDef(item_id, lifetimes) => {
2627 let opaque_ty = tcx.hir().item(item_id);
2628 let def_id = item_id.def_id.to_def_id();
2630 match opaque_ty.kind {
2631 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
2632 self.impl_trait_ty_to_ty(def_id, lifetimes, origin)
2634 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2637 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2638 debug!(?qself, ?segment);
2639 let ty = self.ast_ty_to_ty_inner(qself, false, true);
2640 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, qself, segment, false)
2641 .map(|(ty, _, _)| ty)
2642 .unwrap_or_else(|_| tcx.ty_error())
2644 hir::TyKind::Path(hir::QPath::LangItem(lang_item, span, _)) => {
2645 let def_id = tcx.require_lang_item(lang_item, Some(span));
2646 let (substs, _) = self.create_substs_for_ast_path(
2650 &hir::PathSegment::invalid(),
2651 &GenericArgs::none(),
2655 EarlyBinder(self.normalize_ty(span, tcx.at(span).type_of(def_id)))
2658 hir::TyKind::Array(ref ty, ref length) => {
2659 let length = match length {
2660 &hir::ArrayLen::Infer(_, span) => self.ct_infer(tcx.types.usize, None, span),
2661 hir::ArrayLen::Body(constant) => {
2662 let length_def_id = tcx.hir().local_def_id(constant.hir_id);
2663 ty::Const::from_anon_const(tcx, length_def_id)
2667 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(ty), length));
2668 self.normalize_ty(ast_ty.span, array_ty)
2670 hir::TyKind::Typeof(ref e) => {
2671 let ty = tcx.type_of(tcx.hir().local_def_id(e.hir_id));
2672 let span = ast_ty.span;
2673 tcx.sess.emit_err(TypeofReservedKeywordUsed {
2676 opt_sugg: Some((span, Applicability::MachineApplicable))
2677 .filter(|_| ty.is_suggestable(tcx, false)),
2682 hir::TyKind::Infer => {
2683 // Infer also appears as the type of arguments or return
2684 // values in an ExprKind::Closure, or as
2685 // the type of local variables. Both of these cases are
2686 // handled specially and will not descend into this routine.
2687 self.ty_infer(None, ast_ty.span)
2689 hir::TyKind::Err => tcx.ty_error(),
2694 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2698 fn impl_trait_ty_to_ty(
2701 lifetimes: &[hir::GenericArg<'_>],
2702 origin: OpaqueTyOrigin,
2704 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2705 let tcx = self.tcx();
2707 let generics = tcx.generics_of(def_id);
2709 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2710 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2711 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2712 // Our own parameters are the resolved lifetimes.
2713 if let GenericParamDefKind::Lifetime = param.kind {
2714 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2715 self.ast_region_to_region(lifetime, None).into()
2724 // For RPIT (return position impl trait), only lifetimes
2725 // mentioned in the impl Trait predicate are captured by
2726 // the opaque type, so the lifetime parameters from the
2727 // parent item need to be replaced with `'static`.
2729 // For `impl Trait` in the types of statics, constants,
2730 // locals and type aliases. These capture all parent
2731 // lifetimes, so they can use their identity subst.
2732 GenericParamDefKind::Lifetime
2735 hir::OpaqueTyOrigin::FnReturn(..) | hir::OpaqueTyOrigin::AsyncFn(..)
2738 tcx.lifetimes.re_static.into()
2740 _ => tcx.mk_param_from_def(param),
2744 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2746 let ty = tcx.mk_opaque(def_id, substs);
2747 debug!("impl_trait_ty_to_ty: {}", ty);
2751 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2753 hir::TyKind::Infer if expected_ty.is_some() => {
2754 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2755 expected_ty.unwrap()
2757 _ => self.ast_ty_to_ty(ty),
2764 unsafety: hir::Unsafety,
2766 decl: &hir::FnDecl<'_>,
2767 generics: Option<&hir::Generics<'_>>,
2768 hir_ty: Option<&hir::Ty<'_>>,
2769 ) -> ty::PolyFnSig<'tcx> {
2772 let tcx = self.tcx();
2773 let bound_vars = tcx.late_bound_vars(hir_id);
2774 debug!(?bound_vars);
2776 // We proactively collect all the inferred type params to emit a single error per fn def.
2777 let mut visitor = HirPlaceholderCollector::default();
2778 let mut infer_replacements = vec![];
2780 if let Some(generics) = generics {
2781 walk_generics(&mut visitor, generics);
2784 let input_tys: Vec<_> = decl
2789 if let hir::TyKind::Infer = a.kind && !self.allow_ty_infer() {
2790 if let Some(suggested_ty) =
2791 self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i))
2793 infer_replacements.push((a.span, suggested_ty.to_string()));
2794 return suggested_ty;
2798 // Only visit the type looking for `_` if we didn't fix the type above
2799 visitor.visit_ty(a);
2800 self.ty_of_arg(a, None)
2804 let output_ty = match decl.output {
2805 hir::FnRetTy::Return(output) => {
2806 if let hir::TyKind::Infer = output.kind
2807 && !self.allow_ty_infer()
2808 && let Some(suggested_ty) =
2809 self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, None)
2811 infer_replacements.push((output.span, suggested_ty.to_string()));
2814 visitor.visit_ty(output);
2815 self.ast_ty_to_ty(output)
2818 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2821 debug!("ty_of_fn: output_ty={:?}", output_ty);
2823 let fn_ty = tcx.mk_fn_sig(input_tys.into_iter(), output_ty, decl.c_variadic, unsafety, abi);
2824 let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
2826 if !self.allow_ty_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) {
2827 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2828 // only want to emit an error complaining about them if infer types (`_`) are not
2829 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2830 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2832 let mut diag = crate::collect::placeholder_type_error_diag(
2836 infer_replacements.iter().map(|(s, _)| *s).collect(),
2842 if !infer_replacements.is_empty() {
2843 diag.multipart_suggestion(&format!(
2844 "try replacing `_` with the type{} in the corresponding trait method signature",
2845 rustc_errors::pluralize!(infer_replacements.len()),
2846 ), infer_replacements, Applicability::MachineApplicable);
2852 // Find any late-bound regions declared in return type that do
2853 // not appear in the arguments. These are not well-formed.
2856 // for<'a> fn() -> &'a str <-- 'a is bad
2857 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2858 let inputs = bare_fn_ty.inputs();
2859 let late_bound_in_args =
2860 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2861 let output = bare_fn_ty.output();
2862 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2864 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2869 "return type references {}, which is not constrained by the fn input types",
2877 /// Given a fn_hir_id for a impl function, suggest the type that is found on the
2878 /// corresponding function in the trait that the impl implements, if it exists.
2879 /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
2880 /// corresponds to the return type.
2881 fn suggest_trait_fn_ty_for_impl_fn_infer(
2883 fn_hir_id: hir::HirId,
2884 arg_idx: Option<usize>,
2885 ) -> Option<Ty<'tcx>> {
2886 let tcx = self.tcx();
2887 let hir = tcx.hir();
2889 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
2890 hir.get(fn_hir_id) else { return None };
2891 let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(i), .. }) =
2892 hir.get(hir.get_parent_node(fn_hir_id)) else { bug!("ImplItem should have Impl parent") };
2895 self.instantiate_mono_trait_ref(i.of_trait.as_ref()?, self.ast_ty_to_ty(i.self_ty));
2897 let assoc = tcx.associated_items(trait_ref.def_id).find_by_name_and_kind(
2904 let fn_sig = tcx.bound_fn_sig(assoc.def_id).subst(
2906 trait_ref.substs.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
2909 let ty = if let Some(arg_idx) = arg_idx { fn_sig.input(arg_idx) } else { fn_sig.output() };
2911 Some(tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), ty))
2914 fn validate_late_bound_regions(
2916 constrained_regions: FxHashSet<ty::BoundRegionKind>,
2917 referenced_regions: FxHashSet<ty::BoundRegionKind>,
2918 generate_err: impl Fn(&str) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
2920 for br in referenced_regions.difference(&constrained_regions) {
2921 let br_name = match *br {
2922 ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(_) | ty::BrEnv => {
2923 "an anonymous lifetime".to_string()
2925 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
2928 let mut err = generate_err(&br_name);
2930 if let ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(_) = *br {
2931 // The only way for an anonymous lifetime to wind up
2932 // in the return type but **also** be unconstrained is
2933 // if it only appears in "associated types" in the
2934 // input. See #47511 and #62200 for examples. In this case,
2935 // though we can easily give a hint that ought to be
2938 "lifetimes appearing in an associated type are not considered constrained",
2946 /// Given the bounds on an object, determines what single region bound (if any) we can
2947 /// use to summarize this type. The basic idea is that we will use the bound the user
2948 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2949 /// for region bounds. It may be that we can derive no bound at all, in which case
2950 /// we return `None`.
2951 fn compute_object_lifetime_bound(
2954 existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2955 ) -> Option<ty::Region<'tcx>> // if None, use the default
2957 let tcx = self.tcx();
2959 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2961 // No explicit region bound specified. Therefore, examine trait
2962 // bounds and see if we can derive region bounds from those.
2963 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2965 // If there are no derived region bounds, then report back that we
2966 // can find no region bound. The caller will use the default.
2967 if derived_region_bounds.is_empty() {
2971 // If any of the derived region bounds are 'static, that is always
2973 if derived_region_bounds.iter().any(|r| r.is_static()) {
2974 return Some(tcx.lifetimes.re_static);
2977 // Determine whether there is exactly one unique region in the set
2978 // of derived region bounds. If so, use that. Otherwise, report an
2980 let r = derived_region_bounds[0];
2981 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2982 tcx.sess.emit_err(AmbiguousLifetimeBound { span });
2987 /// Make sure that we are in the condition to suggest the blanket implementation.
2988 fn maybe_lint_blanket_trait_impl(&self, self_ty: &hir::Ty<'_>, diag: &mut Diagnostic) {
2989 let tcx = self.tcx();
2990 let parent_id = tcx.hir().get_parent_item(self_ty.hir_id);
2991 if let hir::Node::Item(hir::Item {
2993 hir::ItemKind::Impl(hir::Impl {
2994 self_ty: impl_self_ty, of_trait: Some(of_trait_ref), generics, ..
2997 }) = tcx.hir().get_by_def_id(parent_id) && self_ty.hir_id == impl_self_ty.hir_id
2999 if !of_trait_ref.trait_def_id().map_or(false, |def_id| def_id.is_local()) {
3002 let of_trait_span = of_trait_ref.path.span;
3003 // make sure that we are not calling unwrap to abort during the compilation
3004 let Ok(impl_trait_name) = tcx.sess.source_map().span_to_snippet(self_ty.span) else { return; };
3005 let Ok(of_trait_name) = tcx.sess.source_map().span_to_snippet(of_trait_span) else { return; };
3006 // check if the trait has generics, to make a correct suggestion
3007 let param_name = generics.params.next_type_param_name(None);
3009 let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() {
3010 (span, format!(", {}: {}", param_name, impl_trait_name))
3012 (generics.span, format!("<{}: {}>", param_name, impl_trait_name))
3014 diag.multipart_suggestion(
3015 format!("alternatively use a blanket \
3016 implementation to implement `{of_trait_name}` for \
3017 all types that also implement `{impl_trait_name}`"),
3019 (self_ty.span, param_name),
3022 Applicability::MaybeIncorrect,
3027 fn maybe_lint_bare_trait(&self, self_ty: &hir::Ty<'_>, in_path: bool) {
3028 let tcx = self.tcx();
3029 if let hir::TyKind::TraitObject([poly_trait_ref, ..], _, TraitObjectSyntax::None) =
3032 let needs_bracket = in_path
3036 .span_to_prev_source(self_ty.span)
3038 .map_or(false, |s| s.trim_end().ends_with('<'));
3040 let is_global = poly_trait_ref.trait_ref.path.is_global();
3041 let sugg = Vec::from_iter([
3043 self_ty.span.shrink_to_lo(),
3046 if needs_bracket { "<" } else { "" },
3047 if is_global { "(" } else { "" },
3051 self_ty.span.shrink_to_hi(),
3054 if is_global { ")" } else { "" },
3055 if needs_bracket { ">" } else { "" },
3059 if self_ty.span.edition() >= Edition::Edition2021 {
3060 let msg = "trait objects must include the `dyn` keyword";
3061 let label = "add `dyn` keyword before this trait";
3063 rustc_errors::struct_span_err!(tcx.sess, self_ty.span, E0782, "{}", msg);
3064 diag.multipart_suggestion_verbose(label, sugg, Applicability::MachineApplicable);
3065 // check if the impl trait that we are considering is a impl of a local trait
3066 self.maybe_lint_blanket_trait_impl(&self_ty, &mut diag);
3069 let msg = "trait objects without an explicit `dyn` are deprecated";
3070 tcx.struct_span_lint_hir(
3075 let mut diag = lint.build(msg);
3076 diag.multipart_suggestion_verbose(
3079 Applicability::MachineApplicable,
3081 self.maybe_lint_blanket_trait_impl(&self_ty, &mut diag);