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, DiagnosticBuilder, ErrorGuaranteed, FatalError,
22 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
23 use rustc_hir::def_id::{DefId, LocalDefId};
24 use rustc_hir::intravisit::{walk_generics, Visitor as _};
25 use rustc_hir::lang_items::LangItem;
26 use rustc_hir::{GenericArg, GenericArgs};
27 use rustc_middle::ty::subst::{self, GenericArgKind, InternalSubsts, Subst, SubstsRef};
28 use rustc_middle::ty::GenericParamDefKind;
29 use rustc_middle::ty::{self, Const, DefIdTree, Ty, TyCtxt, TypeFoldable};
30 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, BARE_TRAIT_OBJECTS};
31 use rustc_span::edition::Edition;
32 use rustc_span::lev_distance::find_best_match_for_name;
33 use rustc_span::symbol::{Ident, Symbol};
34 use rustc_span::{Span, DUMMY_SP};
35 use rustc_target::spec::abi;
36 use rustc_trait_selection::traits;
37 use rustc_trait_selection::traits::astconv_object_safety_violations;
38 use rustc_trait_selection::traits::error_reporting::report_object_safety_error;
39 use rustc_trait_selection::traits::wf::object_region_bounds;
41 use smallvec::SmallVec;
42 use std::collections::BTreeSet;
46 pub struct PathSeg(pub DefId, pub usize);
48 pub trait AstConv<'tcx> {
49 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
51 fn item_def_id(&self) -> Option<DefId>;
53 /// Returns predicates in scope of the form `X: Foo<T>`, where `X`
54 /// is a type parameter `X` with the given id `def_id` and T
55 /// matches `assoc_name`. This is a subset of the full set of
58 /// This is used for one specific purpose: resolving "short-hand"
59 /// associated type references like `T::Item`. In principle, we
60 /// would do that by first getting the full set of predicates in
61 /// scope and then filtering down to find those that apply to `T`,
62 /// but this can lead to cycle errors. The problem is that we have
63 /// to do this resolution *in order to create the predicates in
64 /// the first place*. Hence, we have this "special pass".
65 fn get_type_parameter_bounds(
70 ) -> ty::GenericPredicates<'tcx>;
72 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
73 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
74 -> Option<ty::Region<'tcx>>;
76 /// Returns the type to use when a type is omitted.
77 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
79 /// Returns `true` if `_` is allowed in type signatures in the current context.
80 fn allow_ty_infer(&self) -> bool;
82 /// Returns the const to use when a const is omitted.
86 param: Option<&ty::GenericParamDef>,
90 /// Projecting an associated type from a (potentially)
91 /// higher-ranked trait reference is more complicated, because of
92 /// the possibility of late-bound regions appearing in the
93 /// associated type binding. This is not legal in function
94 /// signatures for that reason. In a function body, we can always
95 /// handle it because we can use inference variables to remove the
96 /// late-bound regions.
97 fn projected_ty_from_poly_trait_ref(
101 item_segment: &hir::PathSegment<'_>,
102 poly_trait_ref: ty::PolyTraitRef<'tcx>,
105 /// Normalize an associated type coming from the user.
106 fn normalize_ty(&self, span: Span, ty: Ty<'tcx>) -> Ty<'tcx>;
108 /// Invoked when we encounter an error from some prior pass
109 /// (e.g., resolve) that is translated into a ty-error. This is
110 /// used to help suppress derived errors typeck might otherwise
112 fn set_tainted_by_errors(&self);
114 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
118 struct ConvertedBinding<'a, 'tcx> {
121 kind: ConvertedBindingKind<'a, 'tcx>,
122 gen_args: &'a GenericArgs<'a>,
127 enum ConvertedBindingKind<'a, 'tcx> {
128 Equality(ty::Term<'tcx>),
129 Constraint(&'a [hir::GenericBound<'a>]),
132 /// New-typed boolean indicating whether explicit late-bound lifetimes
133 /// are present in a set of generic arguments.
135 /// For example if we have some method `fn f<'a>(&'a self)` implemented
136 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
137 /// is late-bound so should not be provided explicitly. Thus, if `f` is
138 /// instantiated with some generic arguments providing `'a` explicitly,
139 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
140 /// can provide an appropriate diagnostic later.
141 #[derive(Copy, Clone, PartialEq)]
142 pub enum ExplicitLateBound {
147 #[derive(Copy, Clone, PartialEq)]
148 pub enum IsMethodCall {
153 /// Denotes the "position" of a generic argument, indicating if it is a generic type,
154 /// generic function or generic method call.
155 #[derive(Copy, Clone, PartialEq)]
156 pub(crate) enum GenericArgPosition {
158 Value, // e.g., functions
162 /// A marker denoting that the generic arguments that were
163 /// provided did not match the respective generic parameters.
164 #[derive(Clone, Default)]
165 pub struct GenericArgCountMismatch {
166 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
167 pub reported: Option<ErrorGuaranteed>,
168 /// A list of spans of arguments provided that were not valid.
169 pub invalid_args: Vec<Span>,
172 /// Decorates the result of a generic argument count mismatch
173 /// check with whether explicit late bounds were provided.
175 pub struct GenericArgCountResult {
176 pub explicit_late_bound: ExplicitLateBound,
177 pub correct: Result<(), GenericArgCountMismatch>,
180 pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> {
181 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
185 param: &ty::GenericParamDef,
186 arg: &GenericArg<'_>,
187 ) -> subst::GenericArg<'tcx>;
191 substs: Option<&[subst::GenericArg<'tcx>]>,
192 param: &ty::GenericParamDef,
194 ) -> subst::GenericArg<'tcx>;
197 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
198 #[tracing::instrument(level = "debug", skip(self))]
199 pub fn ast_region_to_region(
201 lifetime: &hir::Lifetime,
202 def: Option<&ty::GenericParamDef>,
203 ) -> ty::Region<'tcx> {
204 let tcx = self.tcx();
205 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
207 let r = match tcx.named_region(lifetime.hir_id) {
208 Some(rl::Region::Static) => tcx.lifetimes.re_static,
210 Some(rl::Region::LateBound(debruijn, index, def_id)) => {
211 let name = lifetime_name(def_id.expect_local());
212 let br = ty::BoundRegion {
213 var: ty::BoundVar::from_u32(index),
214 kind: ty::BrNamed(def_id, name),
216 tcx.mk_region(ty::ReLateBound(debruijn, br))
219 Some(rl::Region::LateBoundAnon(debruijn, index, anon_index)) => {
220 let br = ty::BoundRegion {
221 var: ty::BoundVar::from_u32(index),
222 kind: ty::BrAnon(anon_index),
224 tcx.mk_region(ty::ReLateBound(debruijn, br))
227 Some(rl::Region::EarlyBound(index, id)) => {
228 let name = lifetime_name(id.expect_local());
229 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id: id, index, name }))
232 Some(rl::Region::Free(scope, id)) => {
233 let name = lifetime_name(id.expect_local());
234 tcx.mk_region(ty::ReFree(ty::FreeRegion {
236 bound_region: ty::BrNamed(id, name),
239 // (*) -- not late-bound, won't change
243 self.re_infer(def, lifetime.span).unwrap_or_else(|| {
244 debug!(?lifetime, "unelided lifetime in signature");
246 // This indicates an illegal lifetime
247 // elision. `resolve_lifetime` should have
248 // reported an error in this case -- but if
249 // not, let's error out.
250 tcx.sess.delay_span_bug(lifetime.span, "unelided lifetime in signature");
252 // Supply some dummy value. We don't have an
253 // `re_error`, annoyingly, so use `'static`.
254 tcx.lifetimes.re_static
259 debug!("ast_region_to_region(lifetime={:?}) yields {:?}", lifetime, r);
264 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
265 /// returns an appropriate set of substitutions for this particular reference to `I`.
266 pub fn ast_path_substs_for_ty(
270 item_segment: &hir::PathSegment<'_>,
271 ) -> SubstsRef<'tcx> {
272 let (substs, _) = self.create_substs_for_ast_path(
278 item_segment.infer_args,
281 let assoc_bindings = self.create_assoc_bindings_for_generic_args(item_segment.args());
283 if let Some(b) = assoc_bindings.first() {
284 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
290 /// Given the type/lifetime/const arguments provided to some path (along with
291 /// an implicit `Self`, if this is a trait reference), returns the complete
292 /// set of substitutions. This may involve applying defaulted type parameters.
293 /// Constraints on associated types are created from `create_assoc_bindings_for_generic_args`.
298 /// T: std::ops::Index<usize, Output = u32>
299 /// ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
302 /// 1. The `self_ty` here would refer to the type `T`.
303 /// 2. The path in question is the path to the trait `std::ops::Index`,
304 /// which will have been resolved to a `def_id`
305 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
306 /// parameters are returned in the `SubstsRef`, the associated type bindings like
307 /// `Output = u32` are returned from `create_assoc_bindings_for_generic_args`.
309 /// Note that the type listing given here is *exactly* what the user provided.
311 /// For (generic) associated types
314 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
317 /// We have the parent substs are the substs for the parent trait:
318 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
319 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
320 /// lists: `[Vec<u8>, u8, 'a]`.
321 #[tracing::instrument(level = "debug", skip(self, span))]
322 fn create_substs_for_ast_path<'a>(
326 parent_substs: &[subst::GenericArg<'tcx>],
327 seg: &hir::PathSegment<'_>,
328 generic_args: &'a hir::GenericArgs<'_>,
330 self_ty: Option<Ty<'tcx>>,
331 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
332 // If the type is parameterized by this region, then replace this
333 // region with the current anon region binding (in other words,
334 // whatever & would get replaced with).
336 let tcx = self.tcx();
337 let generics = tcx.generics_of(def_id);
338 debug!("generics: {:?}", generics);
340 if generics.has_self {
341 if generics.parent.is_some() {
342 // The parent is a trait so it should have at least one subst
343 // for the `Self` type.
344 assert!(!parent_substs.is_empty())
346 // This item (presumably a trait) needs a self-type.
347 assert!(self_ty.is_some());
350 assert!(self_ty.is_none() && parent_substs.is_empty());
353 let arg_count = Self::check_generic_arg_count(
360 GenericArgPosition::Type,
365 // Skip processing if type has no generic parameters.
366 // Traits always have `Self` as a generic parameter, which means they will not return early
367 // here and so associated type bindings will be handled regardless of whether there are any
368 // non-`Self` generic parameters.
369 if generics.params.is_empty() {
370 return (tcx.intern_substs(&[]), arg_count);
373 let is_object = self_ty.map_or(false, |ty| ty == self.tcx().types.trait_object_dummy_self);
375 struct SubstsForAstPathCtxt<'a, 'tcx> {
376 astconv: &'a (dyn AstConv<'tcx> + 'a),
378 generic_args: &'a GenericArgs<'a>,
380 missing_type_params: Vec<String>,
381 inferred_params: Vec<Span>,
386 impl<'tcx, 'a> SubstsForAstPathCtxt<'tcx, 'a> {
387 fn default_needs_object_self(&mut self, param: &ty::GenericParamDef) -> bool {
388 let tcx = self.astconv.tcx();
389 if let GenericParamDefKind::Type { has_default, .. } = param.kind {
390 if self.is_object && has_default {
391 let default_ty = tcx.at(self.span).type_of(param.def_id);
392 let self_param = tcx.types.self_param;
393 if default_ty.walk().any(|arg| arg == self_param.into()) {
394 // There is no suitable inference default for a type parameter
395 // that references self, in an object type.
405 impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> {
406 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) {
407 if did == self.def_id {
408 (Some(self.generic_args), self.infer_args)
410 // The last component of this tuple is unimportant.
417 param: &ty::GenericParamDef,
418 arg: &GenericArg<'_>,
419 ) -> subst::GenericArg<'tcx> {
420 let tcx = self.astconv.tcx();
422 let mut handle_ty_args = |has_default, ty: &hir::Ty<'_>| {
424 tcx.check_optional_stability(
430 // Default generic parameters may not be marked
431 // with stability attributes, i.e. when the
432 // default parameter was defined at the same time
433 // as the rest of the type. As such, we ignore missing
434 // stability attributes.
438 if let (hir::TyKind::Infer, false) = (&ty.kind, self.astconv.allow_ty_infer()) {
439 self.inferred_params.push(ty.span);
440 tcx.ty_error().into()
442 self.astconv.ast_ty_to_ty(ty).into()
446 match (¶m.kind, arg) {
447 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
448 self.astconv.ast_region_to_region(lt, Some(param)).into()
450 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
451 handle_ty_args(has_default, ty)
453 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
454 handle_ty_args(has_default, &inf.to_ty())
456 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
457 ty::Const::from_opt_const_arg_anon_const(
459 ty::WithOptConstParam {
460 did: tcx.hir().local_def_id(ct.value.hir_id),
461 const_param_did: Some(param.def_id),
466 (&GenericParamDefKind::Const { .. }, hir::GenericArg::Infer(inf)) => {
467 let ty = tcx.at(self.span).type_of(param.def_id);
468 if self.astconv.allow_ty_infer() {
469 self.astconv.ct_infer(ty, Some(param), inf.span).into()
471 self.inferred_params.push(inf.span);
472 tcx.const_error(ty).into()
481 substs: Option<&[subst::GenericArg<'tcx>]>,
482 param: &ty::GenericParamDef,
484 ) -> subst::GenericArg<'tcx> {
485 let tcx = self.astconv.tcx();
487 GenericParamDefKind::Lifetime => self
489 .re_infer(Some(param), self.span)
491 debug!(?param, "unelided lifetime in signature");
493 // This indicates an illegal lifetime in a non-assoc-trait position
494 tcx.sess.delay_span_bug(self.span, "unelided lifetime in signature");
496 // Supply some dummy value. We don't have an
497 // `re_error`, annoyingly, so use `'static`.
498 tcx.lifetimes.re_static
501 GenericParamDefKind::Type { has_default, .. } => {
502 if !infer_args && has_default {
503 // No type parameter provided, but a default exists.
505 // If we are converting an object type, then the
506 // `Self` parameter is unknown. However, some of the
507 // other type parameters may reference `Self` in their
508 // defaults. This will lead to an ICE if we are not
510 if self.default_needs_object_self(param) {
511 self.missing_type_params.push(param.name.to_string());
512 tcx.ty_error().into()
514 // This is a default type parameter.
515 let substs = substs.unwrap();
516 if substs.iter().any(|arg| match arg.unpack() {
517 GenericArgKind::Type(ty) => ty.references_error(),
520 // Avoid ICE #86756 when type error recovery goes awry.
521 return tcx.ty_error().into();
526 tcx.at(self.span).type_of(param.def_id).subst_spanned(
534 } else if infer_args {
535 // No type parameters were provided, we can infer all.
536 let param = if !self.default_needs_object_self(param) {
541 self.astconv.ty_infer(param, self.span).into()
543 // We've already errored above about the mismatch.
544 tcx.ty_error().into()
547 GenericParamDefKind::Const { has_default } => {
548 let ty = tcx.at(self.span).type_of(param.def_id);
549 if !infer_args && has_default {
550 tcx.const_param_default(param.def_id)
551 .subst_spanned(tcx, substs.unwrap(), Some(self.span))
555 self.astconv.ct_infer(ty, Some(param), self.span).into()
557 // We've already errored above about the mismatch.
558 tcx.const_error(ty).into()
566 let mut substs_ctx = SubstsForAstPathCtxt {
571 missing_type_params: vec![],
572 inferred_params: vec![],
576 let substs = Self::create_substs_for_generic_args(
586 self.complain_about_missing_type_params(
587 substs_ctx.missing_type_params,
590 generic_args.args.is_empty(),
594 "create_substs_for_ast_path(generic_params={:?}, self_ty={:?}) -> {:?}",
595 generics, self_ty, substs
601 fn create_assoc_bindings_for_generic_args<'a>(
603 generic_args: &'a hir::GenericArgs<'_>,
604 ) -> Vec<ConvertedBinding<'a, 'tcx>> {
605 // Convert associated-type bindings or constraints into a separate vector.
606 // Example: Given this:
608 // T: Iterator<Item = u32>
610 // The `T` is passed in as a self-type; the `Item = u32` is
611 // not a "type parameter" of the `Iterator` trait, but rather
612 // a restriction on `<T as Iterator>::Item`, so it is passed
614 let assoc_bindings = generic_args
618 let kind = match binding.kind {
619 hir::TypeBindingKind::Equality { ref term } => match term {
620 hir::Term::Ty(ref ty) => {
621 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty).into())
623 hir::Term::Const(ref c) => {
624 let local_did = self.tcx().hir().local_def_id(c.hir_id);
625 let c = Const::from_anon_const(self.tcx(), local_did);
626 ConvertedBindingKind::Equality(c.into())
629 hir::TypeBindingKind::Constraint { ref bounds } => {
630 ConvertedBindingKind::Constraint(bounds)
634 hir_id: binding.hir_id,
635 item_name: binding.ident,
637 gen_args: binding.gen_args,
646 crate fn create_substs_for_associated_item(
651 item_segment: &hir::PathSegment<'_>,
652 parent_substs: SubstsRef<'tcx>,
653 ) -> SubstsRef<'tcx> {
655 "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}",
656 span, item_def_id, item_segment
658 if tcx.generics_of(item_def_id).params.is_empty() {
659 self.prohibit_generics(slice::from_ref(item_segment));
663 self.create_substs_for_ast_path(
669 item_segment.infer_args,
676 /// Instantiates the path for the given trait reference, assuming that it's
677 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
678 /// The type _cannot_ be a type other than a trait type.
680 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
681 /// are disallowed. Otherwise, they are pushed onto the vector given.
682 pub fn instantiate_mono_trait_ref(
684 trait_ref: &hir::TraitRef<'_>,
686 ) -> ty::TraitRef<'tcx> {
687 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
689 self.ast_path_to_mono_trait_ref(
691 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
693 trait_ref.path.segments.last().unwrap(),
698 fn instantiate_poly_trait_ref_inner(
702 binding_span: Option<Span>,
703 constness: ty::BoundConstness,
704 bounds: &mut Bounds<'tcx>,
706 trait_ref_span: Span,
708 trait_segment: &hir::PathSegment<'_>,
709 args: &GenericArgs<'_>,
712 ) -> GenericArgCountResult {
713 let (substs, arg_count) = self.create_substs_for_ast_path(
723 let tcx = self.tcx();
724 let bound_vars = tcx.late_bound_vars(hir_id);
727 let assoc_bindings = self.create_assoc_bindings_for_generic_args(args);
730 ty::Binder::bind_with_vars(ty::TraitRef::new(trait_def_id, substs), bound_vars);
732 debug!(?poly_trait_ref, ?assoc_bindings);
733 bounds.trait_bounds.push((poly_trait_ref, span, constness));
735 let mut dup_bindings = FxHashMap::default();
736 for binding in &assoc_bindings {
737 // Specify type to assert that error was already reported in `Err` case.
738 let _: Result<_, ErrorGuaranteed> = self.add_predicates_for_ast_type_binding(
745 binding_span.unwrap_or(binding.span),
747 // Okay to ignore `Err` because of `ErrorGuaranteed` (see above).
753 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
754 /// a full trait reference. The resulting trait reference is returned. This may also generate
755 /// auxiliary bounds, which are added to `bounds`.
760 /// poly_trait_ref = Iterator<Item = u32>
764 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
766 /// **A note on binders:** against our usual convention, there is an implied bounder around
767 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
768 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
769 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
770 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
772 #[tracing::instrument(level = "debug", skip(self, span, constness, bounds, speculative))]
773 pub(crate) fn instantiate_poly_trait_ref(
775 trait_ref: &hir::TraitRef<'_>,
777 constness: ty::BoundConstness,
779 bounds: &mut Bounds<'tcx>,
781 ) -> GenericArgCountResult {
782 let hir_id = trait_ref.hir_ref_id;
783 let binding_span = None;
784 let trait_ref_span = trait_ref.path.span;
785 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
786 let trait_segment = trait_ref.path.segments.last().unwrap();
787 let args = trait_segment.args();
788 let infer_args = trait_segment.infer_args;
790 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1);
791 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, false);
793 self.instantiate_poly_trait_ref_inner(
809 pub(crate) fn instantiate_lang_item_trait_ref(
811 lang_item: hir::LangItem,
814 args: &GenericArgs<'_>,
816 bounds: &mut Bounds<'tcx>,
818 let binding_span = Some(span);
819 let constness = ty::BoundConstness::NotConst;
820 let speculative = false;
821 let trait_ref_span = span;
822 let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
823 let trait_segment = &hir::PathSegment::invalid();
824 let infer_args = false;
826 self.instantiate_poly_trait_ref_inner(
842 fn ast_path_to_mono_trait_ref(
847 trait_segment: &hir::PathSegment<'_>,
849 ) -> ty::TraitRef<'tcx> {
850 let (substs, _) = self.create_substs_for_ast_trait_ref(
857 let assoc_bindings = self.create_assoc_bindings_for_generic_args(trait_segment.args());
858 if let Some(b) = assoc_bindings.first() {
859 Self::prohibit_assoc_ty_binding(self.tcx(), b.span);
861 ty::TraitRef::new(trait_def_id, substs)
864 #[tracing::instrument(level = "debug", skip(self, span))]
865 fn create_substs_for_ast_trait_ref<'a>(
870 trait_segment: &'a hir::PathSegment<'a>,
872 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
873 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
875 self.create_substs_for_ast_path(
880 trait_segment.args(),
881 trait_segment.infer_args,
886 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
888 .associated_items(trait_def_id)
889 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
892 fn trait_defines_associated_const_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
894 .associated_items(trait_def_id)
895 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Const, trait_def_id)
899 // Sets `implicitly_sized` to true on `Bounds` if necessary
900 pub(crate) fn add_implicitly_sized<'hir>(
902 bounds: &mut Bounds<'hir>,
903 ast_bounds: &'hir [hir::GenericBound<'hir>],
904 self_ty_where_predicates: Option<(hir::HirId, &'hir [hir::WherePredicate<'hir>])>,
907 let tcx = self.tcx();
909 // Try to find an unbound in bounds.
910 let mut unbound = None;
911 let mut search_bounds = |ast_bounds: &'hir [hir::GenericBound<'hir>]| {
912 for ab in ast_bounds {
913 if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab {
914 if unbound.is_none() {
915 unbound = Some(&ptr.trait_ref);
917 tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span });
922 search_bounds(ast_bounds);
923 if let Some((self_ty, where_clause)) = self_ty_where_predicates {
924 let self_ty_def_id = tcx.hir().local_def_id(self_ty).to_def_id();
925 for clause in where_clause {
926 if let hir::WherePredicate::BoundPredicate(pred) = clause {
927 match pred.bounded_ty.kind {
928 hir::TyKind::Path(hir::QPath::Resolved(_, path)) => match path.res {
929 Res::Def(DefKind::TyParam, def_id) if def_id == self_ty_def_id => {}
934 search_bounds(pred.bounds);
939 let sized_def_id = tcx.lang_items().require(LangItem::Sized);
940 match (&sized_def_id, unbound) {
941 (Ok(sized_def_id), Some(tpb))
942 if tpb.path.res == Res::Def(DefKind::Trait, *sized_def_id) =>
944 // There was in fact a `?Sized` bound, return without doing anything
948 // There was a `?Trait` bound, but it was not `?Sized`; warn.
951 "default bound relaxed for a type parameter, but \
952 this does nothing because the given bound is not \
953 a default; only `?Sized` is supported",
955 // Otherwise, add implicitly sized if `Sized` is available.
958 // There was no `?Sized` bound; add implicitly sized if `Sized` is available.
961 if sized_def_id.is_err() {
962 // No lang item for `Sized`, so we can't add it as a bound.
965 bounds.implicitly_sized = Some(span);
968 /// This helper takes a *converted* parameter type (`param_ty`)
969 /// and an *unconverted* list of bounds:
973 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
975 /// `param_ty`, in ty form
978 /// It adds these `ast_bounds` into the `bounds` structure.
980 /// **A note on binders:** there is an implied binder around
981 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
982 /// for more details.
983 #[tracing::instrument(level = "debug", skip(self, ast_bounds, bounds))]
984 pub(crate) fn add_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'hir>>>(
988 bounds: &mut Bounds<'tcx>,
989 bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
991 for ast_bound in ast_bounds {
993 hir::GenericBound::Trait(poly_trait_ref, modifier) => {
994 let constness = match modifier {
995 hir::TraitBoundModifier::MaybeConst => ty::BoundConstness::ConstIfConst,
996 hir::TraitBoundModifier::None => ty::BoundConstness::NotConst,
997 hir::TraitBoundModifier::Maybe => continue,
1000 let _ = self.instantiate_poly_trait_ref(
1001 &poly_trait_ref.trait_ref,
1002 poly_trait_ref.span,
1009 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
1010 self.instantiate_lang_item_trait_ref(
1011 lang_item, span, hir_id, args, param_ty, bounds,
1014 hir::GenericBound::Outlives(lifetime) => {
1015 let region = self.ast_region_to_region(lifetime, None);
1018 .push((ty::Binder::bind_with_vars(region, bound_vars), lifetime.span));
1024 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
1025 /// The self-type for the bounds is given by `param_ty`.
1030 /// fn foo<T: Bar + Baz>() { }
1031 /// ^ ^^^^^^^^^ ast_bounds
1035 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
1036 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
1037 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1039 /// `span` should be the declaration size of the parameter.
1040 pub(crate) fn compute_bounds(
1043 ast_bounds: &[hir::GenericBound<'_>],
1045 self.compute_bounds_inner(param_ty, ast_bounds)
1048 /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type
1049 /// named `assoc_name` into ty::Bounds. Ignore the rest.
1050 pub(crate) fn compute_bounds_that_match_assoc_type(
1053 ast_bounds: &[hir::GenericBound<'_>],
1056 let mut result = Vec::new();
1058 for ast_bound in ast_bounds {
1059 if let Some(trait_ref) = ast_bound.trait_ref()
1060 && let Some(trait_did) = trait_ref.trait_def_id()
1061 && self.tcx().trait_may_define_assoc_type(trait_did, assoc_name)
1063 result.push(ast_bound.clone());
1067 self.compute_bounds_inner(param_ty, &result)
1070 fn compute_bounds_inner(
1073 ast_bounds: &[hir::GenericBound<'_>],
1075 let mut bounds = Bounds::default();
1077 self.add_bounds(param_ty, ast_bounds.iter(), &mut bounds, ty::List::empty());
1082 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1085 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1086 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1087 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1088 #[tracing::instrument(
1090 skip(self, bounds, speculative, dup_bindings, path_span)
1092 fn add_predicates_for_ast_type_binding(
1094 hir_ref_id: hir::HirId,
1095 trait_ref: ty::PolyTraitRef<'tcx>,
1096 binding: &ConvertedBinding<'_, 'tcx>,
1097 bounds: &mut Bounds<'tcx>,
1099 dup_bindings: &mut FxHashMap<DefId, Span>,
1101 ) -> Result<(), ErrorGuaranteed> {
1102 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1103 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1104 // subtle in the event that `T` is defined in a supertrait of
1105 // `SomeTrait`, because in that case we need to upcast.
1107 // That is, consider this case:
1110 // trait SubTrait: SuperTrait<i32> { }
1111 // trait SuperTrait<A> { type T; }
1113 // ... B: SubTrait<T = foo> ...
1116 // We want to produce `<B as SuperTrait<i32>>::T == foo`.
1118 let tcx = self.tcx();
1121 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1122 // Simple case: X is defined in the current trait.
1125 // Otherwise, we have to walk through the supertraits to find
1127 self.one_bound_for_assoc_type(
1128 || traits::supertraits(tcx, trait_ref),
1129 || trait_ref.print_only_trait_path().to_string(),
1132 || match binding.kind {
1133 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1139 let (assoc_ident, def_scope) =
1140 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1142 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1143 // of calling `filter_by_name_and_kind`.
1144 let find_item_of_kind = |kind| {
1145 tcx.associated_items(candidate.def_id())
1146 .filter_by_name_unhygienic(assoc_ident.name)
1147 .find(|i| i.kind == kind && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident)
1149 let assoc_item = find_item_of_kind(ty::AssocKind::Type)
1150 .or_else(|| find_item_of_kind(ty::AssocKind::Const))
1151 .expect("missing associated type");
1153 if !assoc_item.vis.is_accessible_from(def_scope, tcx) {
1154 let kind = match assoc_item.kind {
1155 ty::AssocKind::Type => "type",
1156 ty::AssocKind::Const => "const",
1157 _ => unreachable!(),
1162 &format!("associated {kind} `{}` is private", binding.item_name),
1164 .span_label(binding.span, &format!("private associated {kind}"))
1167 tcx.check_stability(assoc_item.def_id, Some(hir_ref_id), binding.span, None);
1171 .entry(assoc_item.def_id)
1172 .and_modify(|prev_span| {
1173 self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified {
1175 prev_span: *prev_span,
1176 item_name: binding.item_name,
1177 def_path: tcx.def_path_str(assoc_item.container.id()),
1180 .or_insert(binding.span);
1183 // Include substitutions for generic parameters of associated types
1184 let projection_ty = candidate.map_bound(|trait_ref| {
1185 let ident = Ident::new(assoc_item.name, binding.item_name.span);
1186 let item_segment = hir::PathSegment {
1188 hir_id: Some(binding.hir_id),
1190 args: Some(binding.gen_args),
1194 let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item(
1203 "add_predicates_for_ast_type_binding: substs for trait-ref and assoc_item: {:?}",
1204 substs_trait_ref_and_assoc_item
1208 item_def_id: assoc_item.def_id,
1209 substs: substs_trait_ref_and_assoc_item,
1214 // Find any late-bound regions declared in `ty` that are not
1215 // declared in the trait-ref or assoc_item. These are not well-formed.
1219 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1220 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1221 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1222 let late_bound_in_trait_ref =
1223 tcx.collect_constrained_late_bound_regions(&projection_ty);
1224 let late_bound_in_ty =
1225 tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty));
1226 debug!("late_bound_in_trait_ref = {:?}", late_bound_in_trait_ref);
1227 debug!("late_bound_in_ty = {:?}", late_bound_in_ty);
1229 // FIXME: point at the type params that don't have appropriate lifetimes:
1230 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1231 // ---- ---- ^^^^^^^
1232 self.validate_late_bound_regions(
1233 late_bound_in_trait_ref,
1240 "binding for associated type `{}` references {}, \
1241 which does not appear in the trait input types",
1250 match binding.kind {
1251 ConvertedBindingKind::Equality(term) => {
1252 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1253 // the "projection predicate" for:
1255 // `<T as Iterator>::Item = u32`
1256 let assoc_item_def_id = projection_ty.skip_binder().item_def_id;
1257 let def_kind = tcx.def_kind(assoc_item_def_id);
1258 match (def_kind, term) {
1259 (hir::def::DefKind::AssocTy, ty::Term::Ty(_))
1260 | (hir::def::DefKind::AssocConst, ty::Term::Const(_)) => (),
1262 let got = if let ty::Term::Ty(_) = term { "type" } else { "const" };
1263 let expected = def_kind.descr(assoc_item_def_id);
1267 &format!("mismatch in bind of {expected}, got {got}"),
1270 tcx.def_span(assoc_item_def_id),
1271 &format!("{expected} defined here does not match {got}"),
1276 bounds.projection_bounds.push((
1277 projection_ty.map_bound(|projection_ty| ty::ProjectionPredicate {
1284 ConvertedBindingKind::Constraint(ast_bounds) => {
1285 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1287 // `<T as Iterator>::Item: Debug`
1289 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1290 // parameter to have a skipped binder.
1291 let param_ty = tcx.mk_ty(ty::Projection(projection_ty.skip_binder()));
1292 self.add_bounds(param_ty, ast_bounds.iter(), bounds, candidate.bound_vars());
1302 item_segment: &hir::PathSegment<'_>,
1304 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1305 self.normalize_ty(span, 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<_>) =
1342 expanded_traits.partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1343 if regular_traits.len() > 1 {
1344 let first_trait = ®ular_traits[0];
1345 let additional_trait = ®ular_traits[1];
1346 let mut err = struct_span_err!(
1348 additional_trait.bottom().1,
1350 "only auto traits can be used as additional traits in a trait object"
1352 additional_trait.label_with_exp_info(
1354 "additional non-auto trait",
1357 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1359 "consider creating a new trait with all of these as supertraits and using that \
1360 trait here instead: `trait NewTrait: {} {{}}`",
1363 .map(|t| t.trait_ref().print_only_trait_path().to_string())
1364 .collect::<Vec<_>>()
1368 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1369 for more information on them, visit \
1370 <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1375 if regular_traits.is_empty() && auto_traits.is_empty() {
1376 tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span });
1377 return tcx.ty_error();
1380 // Check that there are no gross object safety violations;
1381 // most importantly, that the supertraits don't contain `Self`,
1383 for item in ®ular_traits {
1384 let object_safety_violations =
1385 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1386 if !object_safety_violations.is_empty() {
1387 report_object_safety_error(
1390 item.trait_ref().def_id(),
1391 &object_safety_violations,
1394 return tcx.ty_error();
1398 // Use a `BTreeSet` to keep output in a more consistent order.
1399 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1401 let regular_traits_refs_spans = bounds
1404 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1406 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1407 assert_eq!(constness, ty::BoundConstness::NotConst);
1409 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1411 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1412 obligation.predicate
1415 let bound_predicate = obligation.predicate.kind();
1416 match bound_predicate.skip_binder() {
1417 ty::PredicateKind::Trait(pred) => {
1418 let pred = bound_predicate.rebind(pred);
1419 associated_types.entry(span).or_default().extend(
1420 tcx.associated_items(pred.def_id())
1421 .in_definition_order()
1422 .filter(|item| item.kind == ty::AssocKind::Type)
1423 .map(|item| item.def_id),
1426 ty::PredicateKind::Projection(pred) => {
1427 let pred = bound_predicate.rebind(pred);
1428 // A `Self` within the original bound will be substituted with a
1429 // `trait_object_dummy_self`, so check for that.
1430 let references_self = match pred.skip_binder().term {
1431 ty::Term::Ty(ty) => ty.walk().any(|arg| arg == dummy_self.into()),
1432 ty::Term::Const(c) => c.ty().walk().any(|arg| arg == dummy_self.into()),
1435 // If the projection output contains `Self`, force the user to
1436 // elaborate it explicitly to avoid a lot of complexity.
1438 // The "classically useful" case is the following:
1440 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1445 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1446 // but actually supporting that would "expand" to an infinitely-long type
1447 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1449 // Instead, we force the user to write
1450 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1451 // the discussion in #56288 for alternatives.
1452 if !references_self {
1453 // Include projections defined on supertraits.
1454 bounds.projection_bounds.push((pred, span));
1462 for (projection_bound, _) in &bounds.projection_bounds {
1463 for def_ids in associated_types.values_mut() {
1464 def_ids.remove(&projection_bound.projection_def_id());
1468 self.complain_about_missing_associated_types(
1470 potential_assoc_types,
1474 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1475 // `dyn Trait + Send`.
1476 // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering
1478 let mut duplicates = FxHashSet::default();
1479 auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id()));
1480 debug!("regular_traits: {:?}", regular_traits);
1481 debug!("auto_traits: {:?}", auto_traits);
1483 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1484 let existential_trait_refs = regular_traits.iter().map(|i| {
1485 i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| {
1486 if trait_ref.self_ty() != dummy_self {
1487 // FIXME: There appears to be a missing filter on top of `expand_trait_aliases`,
1488 // which picks up non-supertraits where clauses - but also, the object safety
1489 // completely ignores trait aliases, which could be object safety hazards. We
1490 // `delay_span_bug` here to avoid an ICE in stable even when the feature is
1491 // disabled. (#66420)
1492 tcx.sess.delay_span_bug(
1495 "trait_ref_to_existential called on {:?} with non-dummy Self",
1500 ty::ExistentialTraitRef::erase_self_ty(tcx, trait_ref)
1503 let existential_projections = bounds.projection_bounds.iter().map(|(bound, _)| {
1504 bound.map_bound(|b| {
1505 if b.projection_ty.self_ty() != dummy_self {
1506 tcx.sess.delay_span_bug(
1508 &format!("trait_ref_to_existential called on {:?} with non-dummy Self", b),
1511 ty::ExistentialProjection::erase_self_ty(tcx, b)
1515 let regular_trait_predicates = existential_trait_refs
1516 .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait));
1517 let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| {
1518 ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()))
1520 // N.b. principal, projections, auto traits
1521 // FIXME: This is actually wrong with multiple principals in regards to symbol mangling
1522 let mut v = regular_trait_predicates
1524 existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)),
1526 .chain(auto_trait_predicates)
1527 .collect::<SmallVec<[_; 8]>>();
1528 v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
1530 let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter());
1532 // Use explicitly-specified region bound.
1533 let region_bound = if !lifetime.is_elided() {
1534 self.ast_region_to_region(lifetime, None)
1536 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1537 if tcx.named_region(lifetime.hir_id).is_some() {
1538 self.ast_region_to_region(lifetime, None)
1540 self.re_infer(None, span).unwrap_or_else(|| {
1541 let mut err = struct_span_err!(
1545 "the lifetime bound for this object type cannot be deduced \
1546 from context; please supply an explicit bound"
1549 // We will have already emitted an error E0106 complaining about a
1550 // missing named lifetime in `&dyn Trait`, so we elide this one.
1555 tcx.lifetimes.re_static
1560 debug!("region_bound: {:?}", region_bound);
1562 let ty = tcx.mk_dynamic(existential_predicates, region_bound);
1563 debug!("trait_object_type: {:?}", ty);
1567 fn report_ambiguous_associated_type(
1573 ) -> ErrorGuaranteed {
1574 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1575 if let (true, Ok(snippet)) = (
1578 .confused_type_with_std_module
1580 .any(|full_span| full_span.contains(span)),
1581 self.tcx().sess.source_map().span_to_snippet(span),
1583 err.span_suggestion(
1585 "you are looking for the module in `std`, not the primitive type",
1586 format!("std::{}", snippet),
1587 Applicability::MachineApplicable,
1590 err.span_suggestion(
1592 "use fully-qualified syntax",
1593 format!("<{} as {}>::{}", type_str, trait_str, name),
1594 Applicability::HasPlaceholders,
1600 // Search for a bound on a type parameter which includes the associated item
1601 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1602 // This function will fail if there are no suitable bounds or there is
1604 fn find_bound_for_assoc_item(
1606 ty_param_def_id: LocalDefId,
1609 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1610 let tcx = self.tcx();
1613 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1614 ty_param_def_id, assoc_name, span,
1617 let predicates = &self
1618 .get_type_parameter_bounds(span, ty_param_def_id.to_def_id(), assoc_name)
1621 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1623 let param_name = tcx.hir().ty_param_name(ty_param_def_id);
1624 self.one_bound_for_assoc_type(
1626 traits::transitive_bounds_that_define_assoc_type(
1628 predicates.iter().filter_map(|(p, _)| {
1629 Some(p.to_opt_poly_trait_pred()?.map_bound(|t| t.trait_ref))
1634 || param_name.to_string(),
1641 // Checks that `bounds` contains exactly one element and reports appropriate
1642 // errors otherwise.
1643 fn one_bound_for_assoc_type<I>(
1645 all_candidates: impl Fn() -> I,
1646 ty_param_name: impl Fn() -> String,
1649 is_equality: impl Fn() -> Option<String>,
1650 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1652 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1654 let mut matching_candidates = all_candidates()
1655 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1656 let mut const_candidates = all_candidates()
1657 .filter(|r| self.trait_defines_associated_const_named(r.def_id(), assoc_name));
1659 let (bound, next_cand) = match (matching_candidates.next(), const_candidates.next()) {
1660 (Some(bound), _) => (bound, matching_candidates.next()),
1661 (None, Some(bound)) => (bound, const_candidates.next()),
1663 let reported = self.complain_about_assoc_type_not_found(
1669 return Err(reported);
1672 debug!("one_bound_for_assoc_type: bound = {:?}", bound);
1674 if let Some(bound2) = next_cand {
1675 debug!("one_bound_for_assoc_type: bound2 = {:?}", bound2);
1677 let is_equality = is_equality();
1678 let bounds = IntoIterator::into_iter([bound, bound2]).chain(matching_candidates);
1679 let mut err = if is_equality.is_some() {
1680 // More specific Error Index entry.
1685 "ambiguous associated type `{}` in bounds of `{}`",
1694 "ambiguous associated type `{}` in bounds of `{}`",
1699 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1701 let mut where_bounds = vec![];
1702 for bound in bounds {
1703 let bound_id = bound.def_id();
1704 let bound_span = self
1706 .associated_items(bound_id)
1707 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
1708 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1710 if let Some(bound_span) = bound_span {
1714 "ambiguous `{}` from `{}`",
1716 bound.print_only_trait_path(),
1719 if let Some(constraint) = &is_equality {
1720 where_bounds.push(format!(
1721 " T: {trait}::{assoc} = {constraint}",
1722 trait=bound.print_only_trait_path(),
1724 constraint=constraint,
1727 err.span_suggestion_verbose(
1728 span.with_hi(assoc_name.span.lo()),
1729 "use fully qualified syntax to disambiguate",
1733 bound.print_only_trait_path(),
1735 Applicability::MaybeIncorrect,
1740 "associated type `{}` could derive from `{}`",
1742 bound.print_only_trait_path(),
1746 if !where_bounds.is_empty() {
1748 "consider introducing a new type parameter `T` and adding `where` constraints:\
1749 \n where\n T: {},\n{}",
1751 where_bounds.join(",\n"),
1754 let reported = err.emit();
1755 if !where_bounds.is_empty() {
1756 return Err(reported);
1763 // Create a type from a path to an associated type.
1764 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1765 // and item_segment is the path segment for `D`. We return a type and a def for
1767 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1768 // parameter or `Self`.
1769 // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1770 // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
1771 pub fn associated_path_to_ty(
1773 hir_ref_id: hir::HirId,
1777 assoc_segment: &hir::PathSegment<'_>,
1778 permit_variants: bool,
1779 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1780 let tcx = self.tcx();
1781 let assoc_ident = assoc_segment.ident;
1783 debug!("associated_path_to_ty: {:?}::{}", qself_ty, assoc_ident);
1785 // Check if we have an enum variant.
1786 let mut variant_resolution = None;
1787 if let ty::Adt(adt_def, _) = qself_ty.kind() {
1788 if adt_def.is_enum() {
1789 let variant_def = adt_def
1792 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident(tcx), adt_def.did()));
1793 if let Some(variant_def) = variant_def {
1794 if permit_variants {
1795 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None);
1796 self.prohibit_generics(slice::from_ref(assoc_segment));
1797 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1799 variant_resolution = Some(variant_def.def_id);
1805 // Find the type of the associated item, and the trait where the associated
1806 // item is declared.
1807 let bound = match (&qself_ty.kind(), qself_res) {
1808 (_, Res::SelfTy { trait_: Some(_), alias_to: Some((impl_def_id, _)) }) => {
1809 // `Self` in an impl of a trait -- we have a concrete self type and a
1811 let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) else {
1812 // A cycle error occurred, most likely.
1813 let guar = tcx.sess.delay_span_bug(span, "expected cycle error");
1817 self.one_bound_for_assoc_type(
1818 || traits::supertraits(tcx, ty::Binder::dummy(trait_ref)),
1819 || "Self".to_string(),
1827 Res::SelfTy { trait_: Some(param_did), alias_to: None }
1828 | Res::Def(DefKind::TyParam, param_did),
1829 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
1831 let reported = if variant_resolution.is_some() {
1832 // Variant in type position
1833 let msg = format!("expected type, found variant `{}`", assoc_ident);
1834 tcx.sess.span_err(span, &msg)
1835 } else if qself_ty.is_enum() {
1836 let mut err = struct_span_err!(
1840 "no variant named `{}` found for enum `{}`",
1845 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
1846 if let Some(suggested_name) = find_best_match_for_name(
1850 .map(|variant| variant.name)
1851 .collect::<Vec<Symbol>>(),
1855 err.span_suggestion(
1857 "there is a variant with a similar name",
1858 suggested_name.to_string(),
1859 Applicability::MaybeIncorrect,
1864 format!("variant not found in `{}`", qself_ty),
1868 if let Some(sp) = tcx.hir().span_if_local(adt_def.did()) {
1869 let sp = tcx.sess.source_map().guess_head_span(sp);
1870 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
1874 } else if let Some(reported) = qself_ty.error_reported() {
1877 // Don't print `TyErr` to the user.
1878 self.report_ambiguous_associated_type(
1880 &qself_ty.to_string(),
1885 return Err(reported);
1889 let trait_did = bound.def_id();
1890 let (assoc_ident, def_scope) =
1891 tcx.adjust_ident_and_get_scope(assoc_ident, trait_did, hir_ref_id);
1893 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1894 // of calling `filter_by_name_and_kind`.
1895 let item = tcx.associated_items(trait_did).in_definition_order().find(|i| {
1896 i.kind.namespace() == Namespace::TypeNS
1897 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
1899 // Assume that if it's not matched, there must be a const defined with the same name
1900 // but it was used in a type position.
1901 let Some(item) = item else {
1902 let msg = format!("found associated const `{assoc_ident}` when type was expected");
1903 let guar = tcx.sess.struct_span_err(span, &msg).emit();
1907 let ty = self.projected_ty_from_poly_trait_ref(span, item.def_id, assoc_segment, bound);
1908 let ty = self.normalize_ty(span, ty);
1910 let kind = DefKind::AssocTy;
1911 if !item.vis.is_accessible_from(def_scope, tcx) {
1912 let kind = kind.descr(item.def_id);
1913 let msg = format!("{} `{}` is private", kind, assoc_ident);
1915 .struct_span_err(span, &msg)
1916 .span_label(span, &format!("private {}", kind))
1919 tcx.check_stability(item.def_id, Some(hir_ref_id), span, None);
1921 if let Some(variant_def_id) = variant_resolution {
1922 tcx.struct_span_lint_hir(AMBIGUOUS_ASSOCIATED_ITEMS, hir_ref_id, span, |lint| {
1923 let mut err = lint.build("ambiguous associated item");
1924 let mut could_refer_to = |kind: DefKind, def_id, also| {
1925 let note_msg = format!(
1926 "`{}` could{} refer to the {} defined here",
1931 err.span_note(tcx.def_span(def_id), ¬e_msg);
1934 could_refer_to(DefKind::Variant, variant_def_id, "");
1935 could_refer_to(kind, item.def_id, " also");
1937 err.span_suggestion(
1939 "use fully-qualified syntax",
1940 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
1941 Applicability::MachineApplicable,
1947 Ok((ty, kind, item.def_id))
1953 opt_self_ty: Option<Ty<'tcx>>,
1955 trait_segment: &hir::PathSegment<'_>,
1956 item_segment: &hir::PathSegment<'_>,
1958 let tcx = self.tcx();
1960 let trait_def_id = tcx.parent(item_def_id).unwrap();
1962 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
1964 let Some(self_ty) = opt_self_ty else {
1965 let path_str = tcx.def_path_str(trait_def_id);
1967 let def_id = self.item_def_id();
1969 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
1971 let parent_def_id = def_id
1972 .and_then(|def_id| {
1973 def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
1975 .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id());
1977 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
1979 // If the trait in segment is the same as the trait defining the item,
1980 // use the `<Self as ..>` syntax in the error.
1981 let is_part_of_self_trait_constraints = def_id == Some(trait_def_id);
1982 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
1984 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
1990 self.report_ambiguous_associated_type(
1994 item_segment.ident.name,
1996 return tcx.ty_error();
1999 debug!("qpath_to_ty: self_type={:?}", self_ty);
2002 self.ast_path_to_mono_trait_ref(span, trait_def_id, self_ty, trait_segment, false);
2004 let item_substs = self.create_substs_for_associated_item(
2012 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2014 self.normalize_ty(span, tcx.mk_projection(item_def_id, item_substs))
2017 pub fn prohibit_generics<'a, T: IntoIterator<Item = &'a hir::PathSegment<'a>>>(
2021 let mut has_err = false;
2022 for segment in segments {
2023 let (mut err_for_lt, mut err_for_ty, mut err_for_ct) = (false, false, false);
2024 for arg in segment.args().args {
2025 let (span, kind) = match arg {
2026 hir::GenericArg::Lifetime(lt) => {
2032 (lt.span, "lifetime")
2034 hir::GenericArg::Type(ty) => {
2042 hir::GenericArg::Const(ct) => {
2050 hir::GenericArg::Infer(inf) => {
2056 (inf.span, "generic")
2059 let mut err = struct_span_err!(
2063 "{} arguments are not allowed for this type",
2066 err.span_label(span, format!("{} argument not allowed", kind));
2068 if err_for_lt && err_for_ty && err_for_ct {
2073 // Only emit the first error to avoid overloading the user with error messages.
2074 if let [binding, ..] = segment.args().bindings {
2076 Self::prohibit_assoc_ty_binding(self.tcx(), binding.span);
2082 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2083 pub fn def_ids_for_value_path_segments(
2085 segments: &[hir::PathSegment<'_>],
2086 self_ty: Option<Ty<'tcx>>,
2090 // We need to extract the type parameters supplied by the user in
2091 // the path `path`. Due to the current setup, this is a bit of a
2092 // tricky-process; the problem is that resolve only tells us the
2093 // end-point of the path resolution, and not the intermediate steps.
2094 // Luckily, we can (at least for now) deduce the intermediate steps
2095 // just from the end-point.
2097 // There are basically five cases to consider:
2099 // 1. Reference to a constructor of a struct:
2101 // struct Foo<T>(...)
2103 // In this case, the parameters are declared in the type space.
2105 // 2. Reference to a constructor of an enum variant:
2107 // enum E<T> { Foo(...) }
2109 // In this case, the parameters are defined in the type space,
2110 // but may be specified either on the type or the variant.
2112 // 3. Reference to a fn item or a free constant:
2116 // In this case, the path will again always have the form
2117 // `a::b::foo::<T>` where only the final segment should have
2118 // type parameters. However, in this case, those parameters are
2119 // declared on a value, and hence are in the `FnSpace`.
2121 // 4. Reference to a method or an associated constant:
2123 // impl<A> SomeStruct<A> {
2127 // Here we can have a path like
2128 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2129 // may appear in two places. The penultimate segment,
2130 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2131 // final segment, `foo::<B>` contains parameters in fn space.
2133 // The first step then is to categorize the segments appropriately.
2135 let tcx = self.tcx();
2137 assert!(!segments.is_empty());
2138 let last = segments.len() - 1;
2140 let mut path_segs = vec![];
2143 // Case 1. Reference to a struct constructor.
2144 DefKind::Ctor(CtorOf::Struct, ..) => {
2145 // Everything but the final segment should have no
2146 // parameters at all.
2147 let generics = tcx.generics_of(def_id);
2148 // Variant and struct constructors use the
2149 // generics of their parent type definition.
2150 let generics_def_id = generics.parent.unwrap_or(def_id);
2151 path_segs.push(PathSeg(generics_def_id, last));
2154 // Case 2. Reference to a variant constructor.
2155 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2156 let adt_def = self_ty.map(|t| t.ty_adt_def().unwrap());
2157 let (generics_def_id, index) = if let Some(adt_def) = adt_def {
2158 debug_assert!(adt_def.is_enum());
2159 (adt_def.did(), last)
2160 } else if last >= 1 && segments[last - 1].args.is_some() {
2161 // Everything but the penultimate segment should have no
2162 // parameters at all.
2163 let mut def_id = def_id;
2165 // `DefKind::Ctor` -> `DefKind::Variant`
2166 if let DefKind::Ctor(..) = kind {
2167 def_id = tcx.parent(def_id).unwrap()
2170 // `DefKind::Variant` -> `DefKind::Enum`
2171 let enum_def_id = tcx.parent(def_id).unwrap();
2172 (enum_def_id, last - 1)
2174 // FIXME: lint here recommending `Enum::<...>::Variant` form
2175 // instead of `Enum::Variant::<...>` form.
2177 // Everything but the final segment should have no
2178 // parameters at all.
2179 let generics = tcx.generics_of(def_id);
2180 // Variant and struct constructors use the
2181 // generics of their parent type definition.
2182 (generics.parent.unwrap_or(def_id), last)
2184 path_segs.push(PathSeg(generics_def_id, index));
2187 // Case 3. Reference to a top-level value.
2188 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static(_) => {
2189 path_segs.push(PathSeg(def_id, last));
2192 // Case 4. Reference to a method or associated const.
2193 DefKind::AssocFn | DefKind::AssocConst => {
2194 if segments.len() >= 2 {
2195 let generics = tcx.generics_of(def_id);
2196 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2198 path_segs.push(PathSeg(def_id, last));
2201 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2204 debug!("path_segs = {:?}", path_segs);
2209 // Check a type `Path` and convert it to a `Ty`.
2212 opt_self_ty: Option<Ty<'tcx>>,
2213 path: &hir::Path<'_>,
2214 permit_variants: bool,
2216 let tcx = self.tcx();
2219 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2220 path.res, opt_self_ty, path.segments
2223 let span = path.span;
2225 Res::Def(DefKind::OpaqueTy, did) => {
2226 // Check for desugared `impl Trait`.
2227 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2228 let item_segment = path.segments.split_last().unwrap();
2229 self.prohibit_generics(item_segment.1);
2230 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2231 self.normalize_ty(span, tcx.mk_opaque(did, substs))
2238 | DefKind::ForeignTy,
2241 assert_eq!(opt_self_ty, None);
2242 self.prohibit_generics(path.segments.split_last().unwrap().1);
2243 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2245 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2246 // Convert "variant type" as if it were a real type.
2247 // The resulting `Ty` is type of the variant's enum for now.
2248 assert_eq!(opt_self_ty, None);
2251 self.def_ids_for_value_path_segments(path.segments, None, kind, def_id);
2252 let generic_segs: FxHashSet<_> =
2253 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2254 self.prohibit_generics(path.segments.iter().enumerate().filter_map(
2256 if !generic_segs.contains(&index) { Some(seg) } else { None }
2260 let PathSeg(def_id, index) = path_segs.last().unwrap();
2261 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2263 Res::Def(DefKind::TyParam, def_id) => {
2264 assert_eq!(opt_self_ty, None);
2265 self.prohibit_generics(path.segments);
2267 let def_id = def_id.expect_local();
2268 let item_def_id = tcx.hir().ty_param_owner(def_id);
2269 let generics = tcx.generics_of(item_def_id);
2270 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2271 tcx.mk_ty_param(index, tcx.hir().ty_param_name(def_id))
2273 Res::SelfTy { trait_: Some(_), alias_to: None } => {
2274 // `Self` in trait or type alias.
2275 assert_eq!(opt_self_ty, None);
2276 self.prohibit_generics(path.segments);
2277 tcx.types.self_param
2279 Res::SelfTy { trait_: _, alias_to: Some((def_id, forbid_generic)) } => {
2280 // `Self` in impl (we know the concrete type).
2281 assert_eq!(opt_self_ty, None);
2282 self.prohibit_generics(path.segments);
2283 // Try to evaluate any array length constants.
2284 let ty = tcx.at(span).type_of(def_id);
2285 // HACK(min_const_generics): Forbid generic `Self` types
2286 // here as we can't easily do that during nameres.
2288 // We do this before normalization as we otherwise allow
2290 // trait AlwaysApplicable { type Assoc; }
2291 // impl<T: ?Sized> AlwaysApplicable for T { type Assoc = usize; }
2293 // trait BindsParam<T> {
2296 // impl<T> BindsParam<T> for <T as AlwaysApplicable>::Assoc {
2297 // type ArrayTy = [u8; Self::MAX];
2300 // Note that the normalization happens in the param env of
2301 // the anon const, which is empty. This is why the
2302 // `AlwaysApplicable` impl needs a `T: ?Sized` bound for
2303 // this to compile if we were to normalize here.
2304 if forbid_generic && ty.needs_subst() {
2305 let mut err = tcx.sess.struct_span_err(
2307 "generic `Self` types are currently not permitted in anonymous constants",
2309 if let Some(hir::Node::Item(&hir::Item {
2310 kind: hir::ItemKind::Impl(ref impl_),
2312 })) = tcx.hir().get_if_local(def_id)
2314 err.span_note(impl_.self_ty.span, "not a concrete type");
2319 self.normalize_ty(span, ty)
2322 Res::Def(DefKind::AssocTy, def_id) => {
2323 debug_assert!(path.segments.len() >= 2);
2324 self.prohibit_generics(&path.segments[..path.segments.len() - 2]);
2329 &path.segments[path.segments.len() - 2],
2330 path.segments.last().unwrap(),
2333 Res::PrimTy(prim_ty) => {
2334 assert_eq!(opt_self_ty, None);
2335 self.prohibit_generics(path.segments);
2337 hir::PrimTy::Bool => tcx.types.bool,
2338 hir::PrimTy::Char => tcx.types.char,
2339 hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2340 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2341 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2342 hir::PrimTy::Str => tcx.types.str_,
2346 self.set_tainted_by_errors();
2347 self.tcx().ty_error()
2349 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2353 /// Parses the programmer's textual representation of a type into our
2354 /// internal notion of a type.
2355 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2356 self.ast_ty_to_ty_inner(ast_ty, false, false)
2359 /// Parses the programmer's textual representation of a type into our
2360 /// internal notion of a type. This is meant to be used within a path.
2361 pub fn ast_ty_to_ty_in_path(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2362 self.ast_ty_to_ty_inner(ast_ty, false, true)
2365 /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2366 /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2367 #[tracing::instrument(level = "debug", skip(self))]
2368 fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool, in_path: bool) -> Ty<'tcx> {
2369 let tcx = self.tcx();
2371 let result_ty = match ast_ty.kind {
2372 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(ty)),
2373 hir::TyKind::Ptr(ref mt) => {
2374 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl })
2376 hir::TyKind::Rptr(ref region, ref mt) => {
2377 let r = self.ast_region_to_region(region, None);
2379 let t = self.ast_ty_to_ty_inner(mt.ty, true, false);
2380 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2382 hir::TyKind::Never => tcx.types.never,
2383 hir::TyKind::Tup(fields) => tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(t))),
2384 hir::TyKind::BareFn(bf) => {
2385 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span);
2387 tcx.mk_fn_ptr(self.ty_of_fn(
2392 &hir::Generics::empty(),
2397 hir::TyKind::TraitObject(bounds, ref lifetime, _) => {
2398 self.maybe_lint_bare_trait(ast_ty, in_path);
2399 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed)
2401 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2402 debug!(?maybe_qself, ?path);
2403 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2404 self.res_to_ty(opt_self_ty, path, false)
2406 hir::TyKind::OpaqueDef(item_id, lifetimes) => {
2407 let opaque_ty = tcx.hir().item(item_id);
2408 let def_id = item_id.def_id.to_def_id();
2410 match opaque_ty.kind {
2411 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => self
2412 .impl_trait_ty_to_ty(
2417 hir::OpaqueTyOrigin::FnReturn(..)
2418 | hir::OpaqueTyOrigin::AsyncFn(..)
2421 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2424 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2425 debug!(?qself, ?segment);
2426 let ty = self.ast_ty_to_ty_inner(qself, false, true);
2428 let res = if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = qself.kind {
2433 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, res, segment, false)
2434 .map(|(ty, _, _)| ty)
2435 .unwrap_or_else(|_| tcx.ty_error())
2437 hir::TyKind::Path(hir::QPath::LangItem(lang_item, span, _)) => {
2438 let def_id = tcx.require_lang_item(lang_item, Some(span));
2439 let (substs, _) = self.create_substs_for_ast_path(
2443 &hir::PathSegment::invalid(),
2444 &GenericArgs::none(),
2448 self.normalize_ty(span, tcx.at(span).type_of(def_id).subst(tcx, substs))
2450 hir::TyKind::Array(ref ty, ref length) => {
2451 let length = match length {
2452 &hir::ArrayLen::Infer(_, span) => self.ct_infer(tcx.types.usize, None, span),
2453 hir::ArrayLen::Body(constant) => {
2454 let length_def_id = tcx.hir().local_def_id(constant.hir_id);
2455 ty::Const::from_anon_const(tcx, length_def_id)
2459 let array_ty = tcx.mk_ty(ty::Array(self.ast_ty_to_ty(ty), length));
2460 self.normalize_ty(ast_ty.span, array_ty)
2462 hir::TyKind::Typeof(ref e) => {
2463 let ty = tcx.type_of(tcx.hir().local_def_id(e.hir_id));
2464 let span = ast_ty.span;
2465 tcx.sess.emit_err(TypeofReservedKeywordUsed {
2468 opt_sugg: Some((span, Applicability::MachineApplicable))
2469 .filter(|_| ty.is_suggestable()),
2474 hir::TyKind::Infer => {
2475 // Infer also appears as the type of arguments or return
2476 // values in an ExprKind::Closure, or as
2477 // the type of local variables. Both of these cases are
2478 // handled specially and will not descend into this routine.
2479 self.ty_infer(None, ast_ty.span)
2481 hir::TyKind::Err => tcx.ty_error(),
2486 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2490 fn impl_trait_ty_to_ty(
2493 lifetimes: &[hir::GenericArg<'_>],
2494 replace_parent_lifetimes: bool,
2496 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2497 let tcx = self.tcx();
2499 let generics = tcx.generics_of(def_id);
2501 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2502 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2503 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2504 // Our own parameters are the resolved lifetimes.
2505 if let GenericParamDefKind::Lifetime = param.kind {
2506 if let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] {
2507 self.ast_region_to_region(lifetime, None).into()
2516 // For RPIT (return position impl trait), only lifetimes
2517 // mentioned in the impl Trait predicate are captured by
2518 // the opaque type, so the lifetime parameters from the
2519 // parent item need to be replaced with `'static`.
2521 // For `impl Trait` in the types of statics, constants,
2522 // locals and type aliases. These capture all parent
2523 // lifetimes, so they can use their identity subst.
2524 GenericParamDefKind::Lifetime if replace_parent_lifetimes => {
2525 tcx.lifetimes.re_static.into()
2527 _ => tcx.mk_param_from_def(param),
2531 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2533 let ty = tcx.mk_opaque(def_id, substs);
2534 debug!("impl_trait_ty_to_ty: {}", ty);
2538 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2540 hir::TyKind::Infer if expected_ty.is_some() => {
2541 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2542 expected_ty.unwrap()
2544 _ => self.ast_ty_to_ty(ty),
2551 unsafety: hir::Unsafety,
2553 decl: &hir::FnDecl<'_>,
2554 generics: &hir::Generics<'_>,
2555 ident_span: Option<Span>,
2556 hir_ty: Option<&hir::Ty<'_>>,
2557 ) -> ty::PolyFnSig<'tcx> {
2560 let tcx = self.tcx();
2561 let bound_vars = tcx.late_bound_vars(hir_id);
2562 debug!(?bound_vars);
2564 // We proactively collect all the inferred type params to emit a single error per fn def.
2565 let mut visitor = HirPlaceholderCollector::default();
2566 for ty in decl.inputs {
2567 visitor.visit_ty(ty);
2569 walk_generics(&mut visitor, generics);
2571 let input_tys = decl.inputs.iter().map(|a| self.ty_of_arg(a, None));
2572 let output_ty = match decl.output {
2573 hir::FnRetTy::Return(output) => {
2574 visitor.visit_ty(output);
2575 self.ast_ty_to_ty(output)
2577 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2580 debug!("ty_of_fn: output_ty={:?}", output_ty);
2582 let fn_ty = tcx.mk_fn_sig(input_tys, output_ty, decl.c_variadic, unsafety, abi);
2583 let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
2585 if !self.allow_ty_infer() {
2586 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2587 // only want to emit an error complaining about them if infer types (`_`) are not
2588 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2589 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2591 crate::collect::placeholder_type_error(
2593 ident_span.map(|sp| sp.shrink_to_hi()),
2602 // Find any late-bound regions declared in return type that do
2603 // not appear in the arguments. These are not well-formed.
2606 // for<'a> fn() -> &'a str <-- 'a is bad
2607 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2608 let inputs = bare_fn_ty.inputs();
2609 let late_bound_in_args =
2610 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2611 let output = bare_fn_ty.output();
2612 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2614 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2619 "return type references {}, which is not constrained by the fn input types",
2627 fn validate_late_bound_regions(
2629 constrained_regions: FxHashSet<ty::BoundRegionKind>,
2630 referenced_regions: FxHashSet<ty::BoundRegionKind>,
2631 generate_err: impl Fn(&str) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
2633 for br in referenced_regions.difference(&constrained_regions) {
2634 let br_name = match *br {
2635 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
2636 ty::BrAnon(_) | ty::BrEnv => "an anonymous lifetime".to_string(),
2639 let mut err = generate_err(&br_name);
2641 if let ty::BrAnon(_) = *br {
2642 // The only way for an anonymous lifetime to wind up
2643 // in the return type but **also** be unconstrained is
2644 // if it only appears in "associated types" in the
2645 // input. See #47511 and #62200 for examples. In this case,
2646 // though we can easily give a hint that ought to be
2649 "lifetimes appearing in an associated type are not considered constrained",
2657 /// Given the bounds on an object, determines what single region bound (if any) we can
2658 /// use to summarize this type. The basic idea is that we will use the bound the user
2659 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
2660 /// for region bounds. It may be that we can derive no bound at all, in which case
2661 /// we return `None`.
2662 fn compute_object_lifetime_bound(
2665 existential_predicates: &'tcx ty::List<ty::Binder<'tcx, ty::ExistentialPredicate<'tcx>>>,
2666 ) -> Option<ty::Region<'tcx>> // if None, use the default
2668 let tcx = self.tcx();
2670 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
2672 // No explicit region bound specified. Therefore, examine trait
2673 // bounds and see if we can derive region bounds from those.
2674 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
2676 // If there are no derived region bounds, then report back that we
2677 // can find no region bound. The caller will use the default.
2678 if derived_region_bounds.is_empty() {
2682 // If any of the derived region bounds are 'static, that is always
2684 if derived_region_bounds.iter().any(|r| r.is_static()) {
2685 return Some(tcx.lifetimes.re_static);
2688 // Determine whether there is exactly one unique region in the set
2689 // of derived region bounds. If so, use that. Otherwise, report an
2691 let r = derived_region_bounds[0];
2692 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
2693 tcx.sess.emit_err(AmbiguousLifetimeBound { span });
2698 fn maybe_lint_bare_trait(&self, self_ty: &hir::Ty<'_>, in_path: bool) {
2699 let tcx = self.tcx();
2700 if let hir::TyKind::TraitObject([poly_trait_ref, ..], _, TraitObjectSyntax::None) =
2703 let needs_bracket = in_path
2707 .span_to_prev_source(self_ty.span)
2709 .map_or(false, |s| s.trim_end().ends_with('<'));
2711 let is_global = poly_trait_ref.trait_ref.path.is_global();
2712 let sugg = Vec::from_iter([
2714 self_ty.span.shrink_to_lo(),
2717 if needs_bracket { "<" } else { "" },
2718 if is_global { "(" } else { "" },
2722 self_ty.span.shrink_to_hi(),
2725 if is_global { ")" } else { "" },
2726 if needs_bracket { ">" } else { "" },
2730 if self_ty.span.edition() >= Edition::Edition2021 {
2731 let msg = "trait objects must include the `dyn` keyword";
2732 let label = "add `dyn` keyword before this trait";
2733 rustc_errors::struct_span_err!(tcx.sess, self_ty.span, E0782, "{}", msg)
2734 .multipart_suggestion_verbose(label, sugg, Applicability::MachineApplicable)
2737 let msg = "trait objects without an explicit `dyn` are deprecated";
2738 tcx.struct_span_lint_hir(
2744 .multipart_suggestion_verbose(
2747 Applicability::MachineApplicable,