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::astconv::generics::{
9 check_generic_arg_count, create_substs_for_generic_args, prohibit_assoc_ty_binding,
11 use crate::bounds::Bounds;
12 use crate::collect::HirPlaceholderCollector;
14 AmbiguousLifetimeBound, MultipleRelaxedDefaultBounds, TraitObjectDeclaredWithNoTraits,
15 TypeofReservedKeywordUsed, ValueOfAssociatedStructAlreadySpecified,
17 use crate::middle::resolve_lifetime as rl;
18 use crate::require_c_abi_if_c_variadic;
19 use rustc_ast::TraitObjectSyntax;
20 use rustc_data_structures::fx::{FxHashMap, FxHashSet};
22 struct_span_err, Applicability, Diagnostic, DiagnosticBuilder, ErrorGuaranteed, FatalError,
26 use rustc_hir::def::{CtorOf, DefKind, Namespace, Res};
27 use rustc_hir::def_id::{DefId, LocalDefId};
28 use rustc_hir::intravisit::{walk_generics, Visitor as _};
29 use rustc_hir::{GenericArg, GenericArgs, OpaqueTyOrigin};
30 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
31 use rustc_middle::middle::stability::AllowUnstable;
32 use rustc_middle::ty::subst::{self, GenericArgKind, InternalSubsts, SubstsRef};
33 use rustc_middle::ty::GenericParamDefKind;
34 use rustc_middle::ty::{self, Const, DefIdTree, IsSuggestable, Ty, TyCtxt, TypeVisitable};
35 use rustc_middle::ty::{DynKind, EarlyBinder};
36 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, BARE_TRAIT_OBJECTS};
37 use rustc_span::edition::Edition;
38 use rustc_span::lev_distance::find_best_match_for_name;
39 use rustc_span::symbol::{kw, Ident, Symbol};
40 use rustc_span::{sym, Span, DUMMY_SP};
41 use rustc_target::spec::abi;
42 use rustc_trait_selection::traits;
43 use rustc_trait_selection::traits::astconv_object_safety_violations;
44 use rustc_trait_selection::traits::error_reporting::{
45 report_object_safety_error, suggestions::NextTypeParamName,
47 use rustc_trait_selection::traits::wf::object_region_bounds;
49 use smallvec::{smallvec, SmallVec};
50 use std::collections::BTreeSet;
54 pub struct PathSeg(pub DefId, pub usize);
56 pub trait AstConv<'tcx> {
57 fn tcx(&self) -> TyCtxt<'tcx>;
59 fn item_def_id(&self) -> DefId;
61 /// Returns predicates in scope of the form `X: Foo<T>`, where `X`
62 /// is a type parameter `X` with the given id `def_id` and T
63 /// matches `assoc_name`. This is a subset of the full set of
66 /// This is used for one specific purpose: resolving "short-hand"
67 /// associated type references like `T::Item`. In principle, we
68 /// would do that by first getting the full set of predicates in
69 /// scope and then filtering down to find those that apply to `T`,
70 /// but this can lead to cycle errors. The problem is that we have
71 /// to do this resolution *in order to create the predicates in
72 /// the first place*. Hence, we have this "special pass".
73 fn get_type_parameter_bounds(
78 ) -> ty::GenericPredicates<'tcx>;
80 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
81 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
82 -> Option<ty::Region<'tcx>>;
84 /// Returns the type to use when a type is omitted.
85 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
87 /// Returns `true` if `_` is allowed in type signatures in the current context.
88 fn allow_ty_infer(&self) -> bool;
90 /// Returns the const to use when a const is omitted.
94 param: Option<&ty::GenericParamDef>,
98 /// Projecting an associated type from a (potentially)
99 /// higher-ranked trait reference is more complicated, because of
100 /// the possibility of late-bound regions appearing in the
101 /// associated type binding. This is not legal in function
102 /// signatures for that reason. In a function body, we can always
103 /// handle it because we can use inference variables to remove the
104 /// late-bound regions.
105 fn projected_ty_from_poly_trait_ref(
109 item_segment: &hir::PathSegment<'_>,
110 poly_trait_ref: ty::PolyTraitRef<'tcx>,
113 /// Returns `AdtDef` if `ty` is an ADT.
114 /// Note that `ty` might be a projection type that needs normalization.
115 /// This used to get the enum variants in scope of the type.
116 /// For example, `Self::A` could refer to an associated type
117 /// or to an enum variant depending on the result of this function.
118 fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
120 /// Invoked when we encounter an error from some prior pass
121 /// (e.g., resolve) that is translated into a ty-error. This is
122 /// used to help suppress derived errors typeck might otherwise
124 fn set_tainted_by_errors(&self, e: ErrorGuaranteed);
126 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
128 fn astconv(&self) -> &dyn AstConv<'tcx>
135 fn infcx(&self) -> Option<&InferCtxt<'tcx>>;
139 struct ConvertedBinding<'a, 'tcx> {
142 kind: ConvertedBindingKind<'a, 'tcx>,
143 gen_args: &'a GenericArgs<'a>,
148 enum ConvertedBindingKind<'a, 'tcx> {
149 Equality(ty::Term<'tcx>),
150 Constraint(&'a [hir::GenericBound<'a>]),
153 /// New-typed boolean indicating whether explicit late-bound lifetimes
154 /// are present in a set of generic arguments.
156 /// For example if we have some method `fn f<'a>(&'a self)` implemented
157 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
158 /// is late-bound so should not be provided explicitly. Thus, if `f` is
159 /// instantiated with some generic arguments providing `'a` explicitly,
160 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
161 /// can provide an appropriate diagnostic later.
162 #[derive(Copy, Clone, PartialEq, Debug)]
163 pub enum ExplicitLateBound {
168 #[derive(Copy, Clone, PartialEq)]
169 pub enum IsMethodCall {
174 /// Denotes the "position" of a generic argument, indicating if it is a generic type,
175 /// generic function or generic method call.
176 #[derive(Copy, Clone, PartialEq)]
177 pub(crate) enum GenericArgPosition {
179 Value, // e.g., functions
183 /// A marker denoting that the generic arguments that were
184 /// provided did not match the respective generic parameters.
185 #[derive(Clone, Default, Debug)]
186 pub struct GenericArgCountMismatch {
187 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
188 pub reported: Option<ErrorGuaranteed>,
189 /// A list of spans of arguments provided that were not valid.
190 pub invalid_args: Vec<Span>,
193 /// Decorates the result of a generic argument count mismatch
194 /// check with whether explicit late bounds were provided.
195 #[derive(Clone, Debug)]
196 pub struct GenericArgCountResult {
197 pub explicit_late_bound: ExplicitLateBound,
198 pub correct: Result<(), GenericArgCountMismatch>,
201 pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> {
202 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
206 param: &ty::GenericParamDef,
207 arg: &GenericArg<'_>,
208 ) -> subst::GenericArg<'tcx>;
212 substs: Option<&[subst::GenericArg<'tcx>]>,
213 param: &ty::GenericParamDef,
215 ) -> subst::GenericArg<'tcx>;
218 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
219 #[instrument(level = "debug", skip(self), ret)]
220 pub fn ast_region_to_region(
222 lifetime: &hir::Lifetime,
223 def: Option<&ty::GenericParamDef>,
224 ) -> ty::Region<'tcx> {
225 let tcx = self.tcx();
226 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
228 match tcx.named_region(lifetime.hir_id) {
229 Some(rl::Region::Static) => tcx.lifetimes.re_static,
231 Some(rl::Region::LateBound(debruijn, index, def_id)) => {
232 let name = lifetime_name(def_id.expect_local());
233 let br = ty::BoundRegion {
234 var: ty::BoundVar::from_u32(index),
235 kind: ty::BrNamed(def_id, name),
237 tcx.mk_region(ty::ReLateBound(debruijn, br))
240 Some(rl::Region::EarlyBound(def_id)) => {
241 let name = tcx.hir().ty_param_name(def_id.expect_local());
242 let item_def_id = tcx.hir().ty_param_owner(def_id.expect_local());
243 let generics = tcx.generics_of(item_def_id);
244 let index = generics.param_def_id_to_index[&def_id];
245 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, index, name }))
248 Some(rl::Region::Free(scope, id)) => {
249 let name = lifetime_name(id.expect_local());
250 tcx.mk_region(ty::ReFree(ty::FreeRegion {
252 bound_region: ty::BrNamed(id, name),
255 // (*) -- not late-bound, won't change
259 self.re_infer(def, lifetime.ident.span).unwrap_or_else(|| {
260 debug!(?lifetime, "unelided lifetime in signature");
262 // This indicates an illegal lifetime
263 // elision. `resolve_lifetime` should have
264 // reported an error in this case -- but if
265 // not, let's error out.
266 tcx.sess.delay_span_bug(lifetime.ident.span, "unelided lifetime in signature");
268 // Supply some dummy value. We don't have an
269 // `re_error`, annoyingly, so use `'static`.
270 tcx.lifetimes.re_static
276 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
277 /// returns an appropriate set of substitutions for this particular reference to `I`.
278 pub fn ast_path_substs_for_ty(
282 item_segment: &hir::PathSegment<'_>,
283 ) -> SubstsRef<'tcx> {
284 let (substs, _) = self.create_substs_for_ast_path(
290 item_segment.infer_args,
292 ty::BoundConstness::NotConst,
294 if let Some(b) = item_segment.args().bindings.first() {
295 prohibit_assoc_ty_binding(self.tcx(), b.span);
301 /// Given the type/lifetime/const arguments provided to some path (along with
302 /// an implicit `Self`, if this is a trait reference), returns the complete
303 /// set of substitutions. This may involve applying defaulted type parameters.
304 /// Constraints on associated types are created from `create_assoc_bindings_for_generic_args`.
308 /// ```ignore (illustrative)
309 /// T: std::ops::Index<usize, Output = u32>
310 /// // ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
313 /// 1. The `self_ty` here would refer to the type `T`.
314 /// 2. The path in question is the path to the trait `std::ops::Index`,
315 /// which will have been resolved to a `def_id`
316 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
317 /// parameters are returned in the `SubstsRef`, the associated type bindings like
318 /// `Output = u32` are returned from `create_assoc_bindings_for_generic_args`.
320 /// Note that the type listing given here is *exactly* what the user provided.
322 /// For (generic) associated types
324 /// ```ignore (illustrative)
325 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
328 /// We have the parent substs are the substs for the parent trait:
329 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
330 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
331 /// lists: `[Vec<u8>, u8, 'a]`.
332 #[instrument(level = "debug", skip(self, span), ret)]
333 fn create_substs_for_ast_path<'a>(
337 parent_substs: &[subst::GenericArg<'tcx>],
338 seg: &hir::PathSegment<'_>,
339 generic_args: &'a hir::GenericArgs<'_>,
341 self_ty: Option<Ty<'tcx>>,
342 constness: ty::BoundConstness,
343 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
344 // If the type is parameterized by this region, then replace this
345 // region with the current anon region binding (in other words,
346 // whatever & would get replaced with).
348 let tcx = self.tcx();
349 let generics = tcx.generics_of(def_id);
350 debug!("generics: {:?}", generics);
352 if generics.has_self {
353 if generics.parent.is_some() {
354 // The parent is a trait so it should have at least one subst
355 // for the `Self` type.
356 assert!(!parent_substs.is_empty())
358 // This item (presumably a trait) needs a self-type.
359 assert!(self_ty.is_some());
362 assert!(self_ty.is_none());
365 let arg_count = check_generic_arg_count(
372 GenericArgPosition::Type,
377 // Skip processing if type has no generic parameters.
378 // Traits always have `Self` as a generic parameter, which means they will not return early
379 // here and so associated type bindings will be handled regardless of whether there are any
380 // non-`Self` generic parameters.
381 if generics.params.is_empty() {
382 return (tcx.intern_substs(parent_substs), arg_count);
385 struct SubstsForAstPathCtxt<'a, 'tcx> {
386 astconv: &'a (dyn AstConv<'tcx> + 'a),
388 generic_args: &'a GenericArgs<'a>,
390 inferred_params: Vec<Span>,
394 impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> {
395 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) {
396 if did == self.def_id {
397 (Some(self.generic_args), self.infer_args)
399 // The last component of this tuple is unimportant.
406 param: &ty::GenericParamDef,
407 arg: &GenericArg<'_>,
408 ) -> subst::GenericArg<'tcx> {
409 let tcx = self.astconv.tcx();
411 let mut handle_ty_args = |has_default, ty: &hir::Ty<'_>| {
413 tcx.check_optional_stability(
420 // Default generic parameters may not be marked
421 // with stability attributes, i.e. when the
422 // default parameter was defined at the same time
423 // as the rest of the type. As such, we ignore missing
424 // stability attributes.
428 if let (hir::TyKind::Infer, false) = (&ty.kind, self.astconv.allow_ty_infer()) {
429 self.inferred_params.push(ty.span);
430 tcx.ty_error().into()
432 self.astconv.ast_ty_to_ty(ty).into()
436 match (¶m.kind, arg) {
437 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
438 self.astconv.ast_region_to_region(lt, Some(param)).into()
440 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
441 handle_ty_args(has_default, ty)
443 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
444 handle_ty_args(has_default, &inf.to_ty())
446 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
447 ty::Const::from_opt_const_arg_anon_const(
449 ty::WithOptConstParam {
450 did: ct.value.def_id,
451 const_param_did: Some(param.def_id),
456 (&GenericParamDefKind::Const { .. }, hir::GenericArg::Infer(inf)) => {
457 let ty = tcx.at(self.span).type_of(param.def_id);
458 if self.astconv.allow_ty_infer() {
459 self.astconv.ct_infer(ty, Some(param), inf.span).into()
461 self.inferred_params.push(inf.span);
462 tcx.const_error(ty).into()
471 substs: Option<&[subst::GenericArg<'tcx>]>,
472 param: &ty::GenericParamDef,
474 ) -> subst::GenericArg<'tcx> {
475 let tcx = self.astconv.tcx();
477 GenericParamDefKind::Lifetime => self
479 .re_infer(Some(param), self.span)
481 debug!(?param, "unelided lifetime in signature");
483 // This indicates an illegal lifetime in a non-assoc-trait position
484 tcx.sess.delay_span_bug(self.span, "unelided lifetime in signature");
486 // Supply some dummy value. We don't have an
487 // `re_error`, annoyingly, so use `'static`.
488 tcx.lifetimes.re_static
491 GenericParamDefKind::Type { has_default, .. } => {
492 if !infer_args && has_default {
493 // No type parameter provided, but a default exists.
494 let substs = substs.unwrap();
495 if substs.iter().any(|arg| match arg.unpack() {
496 GenericArgKind::Type(ty) => ty.references_error(),
499 // Avoid ICE #86756 when type error recovery goes awry.
500 return tcx.ty_error().into();
502 tcx.at(self.span).bound_type_of(param.def_id).subst(tcx, substs).into()
503 } else if infer_args {
504 self.astconv.ty_infer(Some(param), self.span).into()
506 // We've already errored above about the mismatch.
507 tcx.ty_error().into()
510 GenericParamDefKind::Const { has_default } => {
511 let ty = tcx.at(self.span).type_of(param.def_id);
512 if ty.references_error() {
513 return tcx.const_error(ty).into();
515 if !infer_args && has_default {
516 tcx.const_param_default(param.def_id).subst(tcx, substs.unwrap()).into()
519 self.astconv.ct_infer(ty, Some(param), self.span).into()
521 // We've already errored above about the mismatch.
522 tcx.const_error(ty).into()
530 let mut substs_ctx = SubstsForAstPathCtxt {
535 inferred_params: vec![],
538 let substs = create_substs_for_generic_args(
548 if let ty::BoundConstness::ConstIfConst = constness
549 && generics.has_self && !tcx.has_attr(def_id, sym::const_trait)
551 tcx.sess.emit_err(crate::errors::ConstBoundForNonConstTrait { span } );
557 fn create_assoc_bindings_for_generic_args<'a>(
559 generic_args: &'a hir::GenericArgs<'_>,
560 ) -> Vec<ConvertedBinding<'a, 'tcx>> {
561 // Convert associated-type bindings or constraints into a separate vector.
562 // Example: Given this:
564 // T: Iterator<Item = u32>
566 // The `T` is passed in as a self-type; the `Item = u32` is
567 // not a "type parameter" of the `Iterator` trait, but rather
568 // a restriction on `<T as Iterator>::Item`, so it is passed
570 let assoc_bindings = generic_args
574 let kind = match &binding.kind {
575 hir::TypeBindingKind::Equality { term } => match term {
576 hir::Term::Ty(ty) => {
577 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty).into())
579 hir::Term::Const(c) => {
580 let c = Const::from_anon_const(self.tcx(), c.def_id);
581 ConvertedBindingKind::Equality(c.into())
584 hir::TypeBindingKind::Constraint { bounds } => {
585 ConvertedBindingKind::Constraint(bounds)
589 hir_id: binding.hir_id,
590 item_name: binding.ident,
592 gen_args: binding.gen_args,
601 pub fn create_substs_for_associated_item(
605 item_segment: &hir::PathSegment<'_>,
606 parent_substs: SubstsRef<'tcx>,
607 ) -> SubstsRef<'tcx> {
609 "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}",
610 span, item_def_id, item_segment
612 let (args, _) = self.create_substs_for_ast_path(
618 item_segment.infer_args,
620 ty::BoundConstness::NotConst,
623 if let Some(b) = item_segment.args().bindings.first() {
624 prohibit_assoc_ty_binding(self.tcx(), b.span);
630 /// Instantiates the path for the given trait reference, assuming that it's
631 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
632 /// The type _cannot_ be a type other than a trait type.
634 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
635 /// are disallowed. Otherwise, they are pushed onto the vector given.
636 pub fn instantiate_mono_trait_ref(
638 trait_ref: &hir::TraitRef<'_>,
640 constness: ty::BoundConstness,
641 ) -> ty::TraitRef<'tcx> {
642 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
644 self.ast_path_to_mono_trait_ref(
646 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
648 trait_ref.path.segments.last().unwrap(),
654 fn instantiate_poly_trait_ref_inner(
658 binding_span: Option<Span>,
659 constness: ty::BoundConstness,
660 bounds: &mut Bounds<'tcx>,
662 trait_ref_span: Span,
664 trait_segment: &hir::PathSegment<'_>,
665 args: &GenericArgs<'_>,
668 ) -> GenericArgCountResult {
669 let (substs, arg_count) = self.create_substs_for_ast_path(
680 let tcx = self.tcx();
681 let bound_vars = tcx.late_bound_vars(hir_id);
684 let assoc_bindings = self.create_assoc_bindings_for_generic_args(args);
687 ty::Binder::bind_with_vars(tcx.mk_trait_ref(trait_def_id, substs), bound_vars);
689 debug!(?poly_trait_ref, ?assoc_bindings);
690 bounds.push_trait_bound(tcx, poly_trait_ref, span, constness);
692 let mut dup_bindings = FxHashMap::default();
693 for binding in &assoc_bindings {
694 // Specify type to assert that error was already reported in `Err` case.
695 let _: Result<_, ErrorGuaranteed> = self.add_predicates_for_ast_type_binding(
702 binding_span.unwrap_or(binding.span),
705 // Okay to ignore `Err` because of `ErrorGuaranteed` (see above).
711 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
712 /// a full trait reference. The resulting trait reference is returned. This may also generate
713 /// auxiliary bounds, which are added to `bounds`.
717 /// ```ignore (illustrative)
718 /// poly_trait_ref = Iterator<Item = u32>
722 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
724 /// **A note on binders:** against our usual convention, there is an implied bounder around
725 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
726 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
727 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
728 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
730 #[instrument(level = "debug", skip(self, span, constness, bounds, speculative))]
731 pub(crate) fn instantiate_poly_trait_ref(
733 trait_ref: &hir::TraitRef<'_>,
735 constness: ty::BoundConstness,
737 bounds: &mut Bounds<'tcx>,
739 ) -> GenericArgCountResult {
740 let hir_id = trait_ref.hir_ref_id;
741 let binding_span = None;
742 let trait_ref_span = trait_ref.path.span;
743 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
744 let trait_segment = trait_ref.path.segments.last().unwrap();
745 let args = trait_segment.args();
746 let infer_args = trait_segment.infer_args;
748 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
749 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, false);
751 self.instantiate_poly_trait_ref_inner(
767 pub(crate) fn instantiate_lang_item_trait_ref(
769 lang_item: hir::LangItem,
772 args: &GenericArgs<'_>,
774 bounds: &mut Bounds<'tcx>,
776 let binding_span = Some(span);
777 let constness = ty::BoundConstness::NotConst;
778 let speculative = false;
779 let trait_ref_span = span;
780 let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
781 let trait_segment = &hir::PathSegment::invalid();
782 let infer_args = false;
784 self.instantiate_poly_trait_ref_inner(
800 fn ast_path_to_mono_trait_ref(
805 trait_segment: &hir::PathSegment<'_>,
807 constness: ty::BoundConstness,
808 ) -> ty::TraitRef<'tcx> {
809 let (substs, _) = self.create_substs_for_ast_trait_ref(
817 if let Some(b) = trait_segment.args().bindings.first() {
818 prohibit_assoc_ty_binding(self.tcx(), b.span);
820 self.tcx().mk_trait_ref(trait_def_id, substs)
823 #[instrument(level = "debug", skip(self, span))]
824 fn create_substs_for_ast_trait_ref<'a>(
829 trait_segment: &'a hir::PathSegment<'a>,
831 constness: ty::BoundConstness,
832 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
833 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
835 self.create_substs_for_ast_path(
840 trait_segment.args(),
841 trait_segment.infer_args,
847 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
849 .associated_items(trait_def_id)
850 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
853 fn trait_defines_associated_const_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
855 .associated_items(trait_def_id)
856 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Const, trait_def_id)
860 /// Sets `implicitly_sized` to true on `Bounds` if necessary
861 pub(crate) fn add_implicitly_sized(
863 bounds: &mut Bounds<'tcx>,
865 ast_bounds: &'tcx [hir::GenericBound<'tcx>],
866 self_ty_where_predicates: Option<(LocalDefId, &'tcx [hir::WherePredicate<'tcx>])>,
869 let tcx = self.tcx();
871 // Try to find an unbound in bounds.
872 let mut unbound = None;
873 let mut search_bounds = |ast_bounds: &'tcx [hir::GenericBound<'tcx>]| {
874 for ab in ast_bounds {
875 if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab {
876 if unbound.is_none() {
877 unbound = Some(&ptr.trait_ref);
879 tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span });
884 search_bounds(ast_bounds);
885 if let Some((self_ty, where_clause)) = self_ty_where_predicates {
886 for clause in where_clause {
887 if let hir::WherePredicate::BoundPredicate(pred) = clause {
888 if pred.is_param_bound(self_ty.to_def_id()) {
889 search_bounds(pred.bounds);
895 let sized_def_id = tcx.lang_items().sized_trait();
896 match (&sized_def_id, unbound) {
897 (Some(sized_def_id), Some(tpb))
898 if tpb.path.res == Res::Def(DefKind::Trait, *sized_def_id) =>
900 // There was in fact a `?Sized` bound, return without doing anything
904 // There was a `?Trait` bound, but it was not `?Sized`; warn.
907 "default bound relaxed for a type parameter, but \
908 this does nothing because the given bound is not \
909 a default; only `?Sized` is supported",
911 // Otherwise, add implicitly sized if `Sized` is available.
914 // There was no `?Sized` bound; add implicitly sized if `Sized` is available.
917 if sized_def_id.is_none() {
918 // No lang item for `Sized`, so we can't add it as a bound.
921 bounds.push_sized(tcx, self_ty, span);
924 /// This helper takes a *converted* parameter type (`param_ty`)
925 /// and an *unconverted* list of bounds:
929 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
931 /// `param_ty`, in ty form
934 /// It adds these `ast_bounds` into the `bounds` structure.
936 /// **A note on binders:** there is an implied binder around
937 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
938 /// for more details.
939 #[instrument(level = "debug", skip(self, ast_bounds, bounds))]
940 pub(crate) fn add_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'hir>>>(
944 bounds: &mut Bounds<'tcx>,
945 bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
947 for ast_bound in ast_bounds {
949 hir::GenericBound::Trait(poly_trait_ref, modifier) => {
950 let constness = match modifier {
951 hir::TraitBoundModifier::MaybeConst => ty::BoundConstness::ConstIfConst,
952 hir::TraitBoundModifier::None => ty::BoundConstness::NotConst,
953 hir::TraitBoundModifier::Maybe => continue,
956 let _ = self.instantiate_poly_trait_ref(
957 &poly_trait_ref.trait_ref,
965 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
966 self.instantiate_lang_item_trait_ref(
967 lang_item, span, hir_id, args, param_ty, bounds,
970 hir::GenericBound::Outlives(lifetime) => {
971 let region = self.ast_region_to_region(lifetime, None);
972 bounds.push_region_bound(
974 ty::Binder::bind_with_vars(
975 ty::OutlivesPredicate(param_ty, region),
985 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
986 /// The self-type for the bounds is given by `param_ty`.
990 /// ```ignore (illustrative)
991 /// fn foo<T: Bar + Baz>() { }
992 /// // ^ ^^^^^^^^^ ast_bounds
996 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
997 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
998 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
1000 /// `span` should be the declaration size of the parameter.
1001 pub(crate) fn compute_bounds(
1004 ast_bounds: &[hir::GenericBound<'_>],
1006 self.compute_bounds_inner(param_ty, ast_bounds)
1009 /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type
1010 /// named `assoc_name` into ty::Bounds. Ignore the rest.
1011 pub(crate) fn compute_bounds_that_match_assoc_type(
1014 ast_bounds: &[hir::GenericBound<'_>],
1017 let mut result = Vec::new();
1019 for ast_bound in ast_bounds {
1020 if let Some(trait_ref) = ast_bound.trait_ref()
1021 && let Some(trait_did) = trait_ref.trait_def_id()
1022 && self.tcx().trait_may_define_assoc_type(trait_did, assoc_name)
1024 result.push(ast_bound.clone());
1028 self.compute_bounds_inner(param_ty, &result)
1031 fn compute_bounds_inner(
1034 ast_bounds: &[hir::GenericBound<'_>],
1036 let mut bounds = Bounds::default();
1038 self.add_bounds(param_ty, ast_bounds.iter(), &mut bounds, ty::List::empty());
1044 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1047 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1048 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1049 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1050 #[instrument(level = "debug", skip(self, bounds, speculative, dup_bindings, path_span))]
1051 fn add_predicates_for_ast_type_binding(
1053 hir_ref_id: hir::HirId,
1054 trait_ref: ty::PolyTraitRef<'tcx>,
1055 binding: &ConvertedBinding<'_, 'tcx>,
1056 bounds: &mut Bounds<'tcx>,
1058 dup_bindings: &mut FxHashMap<DefId, Span>,
1060 constness: ty::BoundConstness,
1061 ) -> Result<(), ErrorGuaranteed> {
1062 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1063 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1064 // subtle in the event that `T` is defined in a supertrait of
1065 // `SomeTrait`, because in that case we need to upcast.
1067 // That is, consider this case:
1070 // trait SubTrait: SuperTrait<i32> { }
1071 // trait SuperTrait<A> { type T; }
1073 // ... B: SubTrait<T = foo> ...
1076 // We want to produce `<B as SuperTrait<i32>>::T == foo`.
1078 let tcx = self.tcx();
1081 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1082 // Simple case: X is defined in the current trait.
1085 // Otherwise, we have to walk through the supertraits to find
1087 self.one_bound_for_assoc_type(
1088 || traits::supertraits(tcx, trait_ref),
1089 || trait_ref.print_only_trait_path().to_string(),
1092 || match binding.kind {
1093 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1099 let (assoc_ident, def_scope) =
1100 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1102 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1103 // of calling `filter_by_name_and_kind`.
1104 let find_item_of_kind = |kind| {
1105 tcx.associated_items(candidate.def_id())
1106 .filter_by_name_unhygienic(assoc_ident.name)
1107 .find(|i| i.kind == kind && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident)
1109 let assoc_item = find_item_of_kind(ty::AssocKind::Type)
1110 .or_else(|| find_item_of_kind(ty::AssocKind::Const))
1111 .expect("missing associated type");
1113 if !assoc_item.visibility(tcx).is_accessible_from(def_scope, tcx) {
1117 &format!("{} `{}` is private", assoc_item.kind, binding.item_name),
1119 .span_label(binding.span, &format!("private {}", assoc_item.kind))
1122 tcx.check_stability(assoc_item.def_id, Some(hir_ref_id), binding.span, None);
1126 .entry(assoc_item.def_id)
1127 .and_modify(|prev_span| {
1128 self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified {
1130 prev_span: *prev_span,
1131 item_name: binding.item_name,
1132 def_path: tcx.def_path_str(assoc_item.container_id(tcx)),
1135 .or_insert(binding.span);
1138 // Include substitutions for generic parameters of associated types
1139 let projection_ty = candidate.map_bound(|trait_ref| {
1140 let ident = Ident::new(assoc_item.name, binding.item_name.span);
1141 let item_segment = hir::PathSegment {
1143 hir_id: binding.hir_id,
1145 args: Some(binding.gen_args),
1149 let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item(
1156 debug!(?substs_trait_ref_and_assoc_item);
1158 self.tcx().mk_alias_ty(assoc_item.def_id, substs_trait_ref_and_assoc_item)
1162 // Find any late-bound regions declared in `ty` that are not
1163 // declared in the trait-ref or assoc_item. These are not well-formed.
1167 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1168 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1169 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1170 let late_bound_in_trait_ref =
1171 tcx.collect_constrained_late_bound_regions(&projection_ty);
1172 let late_bound_in_ty =
1173 tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty));
1174 debug!(?late_bound_in_trait_ref);
1175 debug!(?late_bound_in_ty);
1177 // FIXME: point at the type params that don't have appropriate lifetimes:
1178 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1179 // ---- ---- ^^^^^^^
1180 self.validate_late_bound_regions(
1181 late_bound_in_trait_ref,
1188 "binding for associated type `{}` references {}, \
1189 which does not appear in the trait input types",
1198 match binding.kind {
1199 ConvertedBindingKind::Equality(mut term) => {
1200 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1201 // the "projection predicate" for:
1203 // `<T as Iterator>::Item = u32`
1204 let assoc_item_def_id = projection_ty.skip_binder().def_id;
1205 let def_kind = tcx.def_kind(assoc_item_def_id);
1206 match (def_kind, term.unpack()) {
1207 (hir::def::DefKind::AssocTy, ty::TermKind::Ty(_))
1208 | (hir::def::DefKind::AssocConst, ty::TermKind::Const(_)) => (),
1210 let got = if let Some(_) = term.ty() { "type" } else { "constant" };
1211 let expected = def_kind.descr(assoc_item_def_id);
1212 let mut err = tcx.sess.struct_span_err(
1214 &format!("expected {expected} bound, found {got}"),
1217 tcx.def_span(assoc_item_def_id),
1218 &format!("{expected} defined here"),
1221 if let hir::def::DefKind::AssocConst = def_kind
1222 && let Some(t) = term.ty() && (t.is_enum() || t.references_error())
1223 && tcx.features().associated_const_equality {
1224 err.span_suggestion(
1226 "if equating a const, try wrapping with braces",
1227 format!("{} = {{ const }}", binding.item_name),
1228 Applicability::HasPlaceholders,
1231 let reported = err.emit();
1232 term = match def_kind {
1233 hir::def::DefKind::AssocTy => {
1234 tcx.ty_error_with_guaranteed(reported).into()
1236 hir::def::DefKind::AssocConst => tcx
1237 .const_error_with_guaranteed(
1238 tcx.bound_type_of(assoc_item_def_id)
1239 .subst(tcx, projection_ty.skip_binder().substs),
1243 _ => unreachable!(),
1247 bounds.push_projection_bound(
1250 .map_bound(|projection_ty| ty::ProjectionPredicate { projection_ty, term }),
1254 ConvertedBindingKind::Constraint(ast_bounds) => {
1255 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1257 // `<T as Iterator>::Item: Debug`
1259 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1260 // parameter to have a skipped binder.
1261 let param_ty = tcx.mk_ty(ty::Alias(ty::Projection, projection_ty.skip_binder()));
1262 self.add_bounds(param_ty, ast_bounds.iter(), bounds, candidate.bound_vars());
1272 item_segment: &hir::PathSegment<'_>,
1274 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1275 self.tcx().at(span).bound_type_of(did).subst(self.tcx(), substs)
1278 fn conv_object_ty_poly_trait_ref(
1281 hir_trait_bounds: &[hir::PolyTraitRef<'_>],
1282 lifetime: &hir::Lifetime,
1284 representation: DynKind,
1286 let tcx = self.tcx();
1288 let mut bounds = Bounds::default();
1289 let mut potential_assoc_types = Vec::new();
1290 let dummy_self = self.tcx().types.trait_object_dummy_self;
1291 for trait_bound in hir_trait_bounds.iter().rev() {
1292 if let GenericArgCountResult {
1294 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1296 } = self.instantiate_poly_trait_ref(
1297 &trait_bound.trait_ref,
1299 ty::BoundConstness::NotConst,
1304 potential_assoc_types.extend(cur_potential_assoc_types);
1308 let mut trait_bounds = vec![];
1309 let mut projection_bounds = vec![];
1310 for (pred, span) in bounds.predicates() {
1311 let bound_pred = pred.kind();
1312 match bound_pred.skip_binder() {
1313 ty::PredicateKind::Clause(clause) => match clause {
1314 ty::Clause::Trait(trait_pred) => {
1315 assert_eq!(trait_pred.polarity, ty::ImplPolarity::Positive);
1317 bound_pred.rebind(trait_pred.trait_ref),
1319 trait_pred.constness,
1322 ty::Clause::Projection(proj) => {
1323 projection_bounds.push((bound_pred.rebind(proj), span));
1325 ty::Clause::TypeOutlives(_) => {
1326 // Do nothing, we deal with regions separately
1328 ty::Clause::RegionOutlives(_) => bug!(),
1330 ty::PredicateKind::WellFormed(_)
1331 | ty::PredicateKind::ObjectSafe(_)
1332 | ty::PredicateKind::ClosureKind(_, _, _)
1333 | ty::PredicateKind::Subtype(_)
1334 | ty::PredicateKind::Coerce(_)
1335 | ty::PredicateKind::ConstEvaluatable(_)
1336 | ty::PredicateKind::ConstEquate(_, _)
1337 | ty::PredicateKind::TypeWellFormedFromEnv(_)
1338 | ty::PredicateKind::Ambiguous => bug!(),
1342 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1343 // is used and no 'maybe' bounds are used.
1344 let expanded_traits =
1345 traits::expand_trait_aliases(tcx, trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1347 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) = expanded_traits
1348 .filter(|i| i.trait_ref().self_ty().skip_binder() == dummy_self)
1349 .partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1350 if regular_traits.len() > 1 {
1351 let first_trait = ®ular_traits[0];
1352 let additional_trait = ®ular_traits[1];
1353 let mut err = struct_span_err!(
1355 additional_trait.bottom().1,
1357 "only auto traits can be used as additional traits in a trait object"
1359 additional_trait.label_with_exp_info(
1361 "additional non-auto trait",
1364 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1366 "consider creating a new trait with all of these as supertraits and using that \
1367 trait here instead: `trait NewTrait: {} {{}}`",
1370 .map(|t| t.trait_ref().print_only_trait_path().to_string())
1371 .collect::<Vec<_>>()
1375 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1376 for more information on them, visit \
1377 <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1382 if regular_traits.is_empty() && auto_traits.is_empty() {
1383 let trait_alias_span = trait_bounds
1385 .map(|&(trait_ref, _, _)| trait_ref.def_id())
1386 .find(|&trait_ref| tcx.is_trait_alias(trait_ref))
1387 .map(|trait_ref| tcx.def_span(trait_ref));
1389 tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span, trait_alias_span });
1390 return tcx.ty_error_with_guaranteed(reported);
1393 // Check that there are no gross object safety violations;
1394 // most importantly, that the supertraits don't contain `Self`,
1396 for item in ®ular_traits {
1397 let object_safety_violations =
1398 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1399 if !object_safety_violations.is_empty() {
1400 let reported = report_object_safety_error(
1403 item.trait_ref().def_id(),
1404 &object_safety_violations,
1407 return tcx.ty_error_with_guaranteed(reported);
1411 // Use a `BTreeSet` to keep output in a more consistent order.
1412 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1414 let regular_traits_refs_spans = trait_bounds
1416 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1418 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1419 assert_eq!(constness, ty::BoundConstness::NotConst);
1421 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1423 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1424 obligation.predicate
1427 let bound_predicate = obligation.predicate.kind();
1428 match bound_predicate.skip_binder() {
1429 ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => {
1430 let pred = bound_predicate.rebind(pred);
1431 associated_types.entry(span).or_default().extend(
1432 tcx.associated_items(pred.def_id())
1433 .in_definition_order()
1434 .filter(|item| item.kind == ty::AssocKind::Type)
1435 .map(|item| item.def_id),
1438 ty::PredicateKind::Clause(ty::Clause::Projection(pred)) => {
1439 let pred = bound_predicate.rebind(pred);
1440 // A `Self` within the original bound will be substituted with a
1441 // `trait_object_dummy_self`, so check for that.
1442 let references_self = match pred.skip_binder().term.unpack() {
1443 ty::TermKind::Ty(ty) => ty.walk().any(|arg| arg == dummy_self.into()),
1444 ty::TermKind::Const(c) => {
1445 c.ty().walk().any(|arg| arg == dummy_self.into())
1449 // If the projection output contains `Self`, force the user to
1450 // elaborate it explicitly to avoid a lot of complexity.
1452 // The "classically useful" case is the following:
1454 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1459 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1460 // but actually supporting that would "expand" to an infinitely-long type
1461 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1463 // Instead, we force the user to write
1464 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1465 // the discussion in #56288 for alternatives.
1466 if !references_self {
1467 // Include projections defined on supertraits.
1468 projection_bounds.push((pred, span));
1476 for (projection_bound, _) in &projection_bounds {
1477 for def_ids in associated_types.values_mut() {
1478 def_ids.remove(&projection_bound.projection_def_id());
1482 self.complain_about_missing_associated_types(
1484 potential_assoc_types,
1488 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1489 // `dyn Trait + Send`.
1490 // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering
1492 let mut duplicates = FxHashSet::default();
1493 auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id()));
1494 debug!("regular_traits: {:?}", regular_traits);
1495 debug!("auto_traits: {:?}", auto_traits);
1497 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1498 let existential_trait_refs = regular_traits.iter().map(|i| {
1499 i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| {
1500 assert_eq!(trait_ref.self_ty(), dummy_self);
1502 // Verify that `dummy_self` did not leak inside default type parameters. This
1503 // could not be done at path creation, since we need to see through trait aliases.
1504 let mut missing_type_params = vec![];
1505 let mut references_self = false;
1506 let generics = tcx.generics_of(trait_ref.def_id);
1507 let substs: Vec<_> = trait_ref
1511 .skip(1) // Remove `Self` for `ExistentialPredicate`.
1512 .map(|(index, arg)| {
1513 if arg == dummy_self.into() {
1514 let param = &generics.params[index];
1515 missing_type_params.push(param.name);
1516 return tcx.ty_error().into();
1517 } else if arg.walk().any(|arg| arg == dummy_self.into()) {
1518 references_self = true;
1519 return tcx.ty_error().into();
1524 let substs = tcx.intern_substs(&substs[..]);
1526 let span = i.bottom().1;
1527 let empty_generic_args = hir_trait_bounds.iter().any(|hir_bound| {
1528 hir_bound.trait_ref.path.res == Res::Def(DefKind::Trait, trait_ref.def_id)
1529 && hir_bound.span.contains(span)
1531 self.complain_about_missing_type_params(
1532 missing_type_params,
1538 if references_self {
1539 let def_id = i.bottom().0.def_id();
1540 let mut err = struct_span_err!(
1544 "the {} `{}` cannot be made into an object",
1545 tcx.def_kind(def_id).descr(def_id),
1546 tcx.item_name(def_id),
1549 rustc_middle::traits::ObjectSafetyViolation::SupertraitSelf(smallvec![])
1555 ty::ExistentialTraitRef { def_id: trait_ref.def_id, substs }
1559 let existential_projections = projection_bounds.iter().map(|(bound, _)| {
1560 bound.map_bound(|mut b| {
1561 assert_eq!(b.projection_ty.self_ty(), dummy_self);
1563 // Like for trait refs, verify that `dummy_self` did not leak inside default type
1565 let references_self = b.projection_ty.substs.iter().skip(1).any(|arg| {
1566 if arg.walk().any(|arg| arg == dummy_self.into()) {
1571 if references_self {
1573 .delay_span_bug(span, "trait object projection bounds reference `Self`");
1574 let substs: Vec<_> = b
1579 if arg.walk().any(|arg| arg == dummy_self.into()) {
1580 return tcx.ty_error().into();
1585 b.projection_ty.substs = tcx.intern_substs(&substs[..]);
1588 ty::ExistentialProjection::erase_self_ty(tcx, b)
1592 let regular_trait_predicates = existential_trait_refs
1593 .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait));
1594 let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| {
1595 ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()))
1597 // N.b. principal, projections, auto traits
1598 // FIXME: This is actually wrong with multiple principals in regards to symbol mangling
1599 let mut v = regular_trait_predicates
1601 existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)),
1603 .chain(auto_trait_predicates)
1604 .collect::<SmallVec<[_; 8]>>();
1605 v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
1607 let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter());
1609 // Use explicitly-specified region bound.
1610 let region_bound = if !lifetime.is_elided() {
1611 self.ast_region_to_region(lifetime, None)
1613 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1614 if tcx.named_region(lifetime.hir_id).is_some() {
1615 self.ast_region_to_region(lifetime, None)
1617 self.re_infer(None, span).unwrap_or_else(|| {
1618 let mut err = struct_span_err!(
1622 "the lifetime bound for this object type cannot be deduced \
1623 from context; please supply an explicit bound"
1626 // We will have already emitted an error E0106 complaining about a
1627 // missing named lifetime in `&dyn Trait`, so we elide this one.
1632 tcx.lifetimes.re_static
1637 debug!("region_bound: {:?}", region_bound);
1639 let ty = tcx.mk_dynamic(existential_predicates, region_bound, representation);
1640 debug!("trait_object_type: {:?}", ty);
1644 fn report_ambiguous_associated_type(
1650 ) -> ErrorGuaranteed {
1651 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1655 .confused_type_with_std_module
1657 .any(|full_span| full_span.contains(span))
1659 err.span_suggestion_verbose(
1660 span.shrink_to_lo(),
1661 "you are looking for the module in `std`, not the primitive type",
1663 Applicability::MachineApplicable,
1666 match (types, traits) {
1668 err.span_suggestion_verbose(
1671 "if there were a type named `Type` that implements a trait named \
1672 `Trait` with associated type `{name}`, you could use the \
1673 fully-qualified path",
1675 format!("<Type as Trait>::{name}"),
1676 Applicability::HasPlaceholders,
1679 ([], [trait_str]) => {
1680 err.span_suggestion_verbose(
1683 "if there were a type named `Example` that implemented `{trait_str}`, \
1684 you could use the fully-qualified path",
1686 format!("<Example as {trait_str}>::{name}"),
1687 Applicability::HasPlaceholders,
1691 err.span_suggestions(
1694 "if there were a type named `Example` that implemented one of the \
1695 traits with associated type `{name}`, you could use the \
1696 fully-qualified path",
1700 .map(|trait_str| format!("<Example as {trait_str}>::{name}"))
1701 .collect::<Vec<_>>(),
1702 Applicability::HasPlaceholders,
1705 ([type_str], []) => {
1706 err.span_suggestion_verbose(
1709 "if there were a trait named `Example` with associated type `{name}` \
1710 implemented for `{type_str}`, you could use the fully-qualified path",
1712 format!("<{type_str} as Example>::{name}"),
1713 Applicability::HasPlaceholders,
1717 err.span_suggestions(
1720 "if there were a trait named `Example` with associated type `{name}` \
1721 implemented for one of the types, you could use the fully-qualified \
1726 .map(|type_str| format!("<{type_str} as Example>::{name}")),
1727 Applicability::HasPlaceholders,
1730 (types, traits) => {
1731 let mut suggestions = vec![];
1732 for type_str in types {
1733 for trait_str in traits {
1734 suggestions.push(format!("<{type_str} as {trait_str}>::{name}"));
1737 err.span_suggestions(
1739 "use the fully-qualified path",
1741 Applicability::MachineApplicable,
1749 // Search for a bound on a type parameter which includes the associated item
1750 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1751 // This function will fail if there are no suitable bounds or there is
1753 fn find_bound_for_assoc_item(
1755 ty_param_def_id: LocalDefId,
1758 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1759 let tcx = self.tcx();
1762 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1763 ty_param_def_id, assoc_name, span,
1766 let predicates = &self
1767 .get_type_parameter_bounds(span, ty_param_def_id.to_def_id(), assoc_name)
1770 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1772 let param_name = tcx.hir().ty_param_name(ty_param_def_id);
1773 self.one_bound_for_assoc_type(
1775 traits::transitive_bounds_that_define_assoc_type(
1777 predicates.iter().filter_map(|(p, _)| {
1778 Some(p.to_opt_poly_trait_pred()?.map_bound(|t| t.trait_ref))
1783 || param_name.to_string(),
1790 // Checks that `bounds` contains exactly one element and reports appropriate
1791 // errors otherwise.
1792 #[instrument(level = "debug", skip(self, all_candidates, ty_param_name, is_equality), ret)]
1793 fn one_bound_for_assoc_type<I>(
1795 all_candidates: impl Fn() -> I,
1796 ty_param_name: impl Fn() -> String,
1799 is_equality: impl Fn() -> Option<String>,
1800 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1802 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1804 let mut matching_candidates = all_candidates()
1805 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1806 let mut const_candidates = all_candidates()
1807 .filter(|r| self.trait_defines_associated_const_named(r.def_id(), assoc_name));
1809 let (bound, next_cand) = match (matching_candidates.next(), const_candidates.next()) {
1810 (Some(bound), _) => (bound, matching_candidates.next()),
1811 (None, Some(bound)) => (bound, const_candidates.next()),
1813 let reported = self.complain_about_assoc_type_not_found(
1819 return Err(reported);
1824 if let Some(bound2) = next_cand {
1827 let is_equality = is_equality();
1828 let bounds = IntoIterator::into_iter([bound, bound2]).chain(matching_candidates);
1829 let mut err = if is_equality.is_some() {
1830 // More specific Error Index entry.
1835 "ambiguous associated type `{}` in bounds of `{}`",
1844 "ambiguous associated type `{}` in bounds of `{}`",
1849 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1851 let mut where_bounds = vec![];
1852 for bound in bounds {
1853 let bound_id = bound.def_id();
1854 let bound_span = self
1856 .associated_items(bound_id)
1857 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
1858 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1860 if let Some(bound_span) = bound_span {
1864 "ambiguous `{}` from `{}`",
1866 bound.print_only_trait_path(),
1869 if let Some(constraint) = &is_equality {
1870 where_bounds.push(format!(
1871 " T: {trait}::{assoc} = {constraint}",
1872 trait=bound.print_only_trait_path(),
1874 constraint=constraint,
1877 err.span_suggestion_verbose(
1878 span.with_hi(assoc_name.span.lo()),
1879 "use fully qualified syntax to disambiguate",
1883 bound.print_only_trait_path(),
1885 Applicability::MaybeIncorrect,
1890 "associated type `{}` could derive from `{}`",
1892 bound.print_only_trait_path(),
1896 if !where_bounds.is_empty() {
1898 "consider introducing a new type parameter `T` and adding `where` constraints:\
1899 \n where\n T: {},\n{}",
1901 where_bounds.join(",\n"),
1904 let reported = err.emit();
1905 if !where_bounds.is_empty() {
1906 return Err(reported);
1913 // Create a type from a path to an associated type or to an enum variant.
1914 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1915 // and item_segment is the path segment for `D`. We return a type and a def for
1917 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1918 // parameter or `Self`.
1919 // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1920 // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
1921 #[instrument(level = "debug", skip(self, hir_ref_id, span, qself, assoc_segment), fields(assoc_ident=?assoc_segment.ident), ret)]
1922 pub fn associated_path_to_ty(
1924 hir_ref_id: hir::HirId,
1927 qself: &hir::Ty<'_>,
1928 assoc_segment: &hir::PathSegment<'_>,
1929 permit_variants: bool,
1930 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1931 let tcx = self.tcx();
1932 let assoc_ident = assoc_segment.ident;
1933 let qself_res = if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &qself.kind {
1939 // Check if we have an enum variant.
1940 let mut variant_resolution = None;
1941 if let Some(adt_def) = self.probe_adt(span, qself_ty) {
1942 if adt_def.is_enum() {
1943 let variant_def = adt_def
1946 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident(tcx), adt_def.did()));
1947 if let Some(variant_def) = variant_def {
1948 if permit_variants {
1949 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None);
1950 self.prohibit_generics(slice::from_ref(assoc_segment).iter(), |err| {
1951 err.note("enum variants can't have type parameters");
1952 let type_name = tcx.item_name(adt_def.did());
1954 "you might have meant to specity type parameters on enum \
1957 let Some(args) = assoc_segment.args else { return; };
1958 // Get the span of the generics args *including* the leading `::`.
1959 let args_span = assoc_segment.ident.span.shrink_to_hi().to(args.span_ext);
1960 if tcx.generics_of(adt_def.did()).count() == 0 {
1961 // FIXME(estebank): we could also verify that the arguments being
1962 // work for the `enum`, instead of just looking if it takes *any*.
1963 err.span_suggestion_verbose(
1965 &format!("{type_name} doesn't have generic parameters"),
1967 Applicability::MachineApplicable,
1971 let Ok(snippet) = tcx.sess.source_map().span_to_snippet(args_span) else {
1975 let (qself_sugg_span, is_self) = if let hir::TyKind::Path(
1976 hir::QPath::Resolved(_, path)
1978 // If the path segment already has type params, we want to overwrite
1980 match &path.segments[..] {
1981 // `segment` is the previous to last element on the path,
1982 // which would normally be the `enum` itself, while the last
1983 // `_` `PathSegment` corresponds to the variant.
1984 [.., hir::PathSegment {
1987 res: Res::Def(DefKind::Enum, _),
1990 // We need to include the `::` in `Type::Variant::<Args>`
1991 // to point the span to `::<Args>`, not just `<Args>`.
1992 ident.span.shrink_to_hi().to(args.map_or(
1993 ident.span.shrink_to_hi(),
1998 // We need to include the `::` in `Type::Variant::<Args>`
1999 // to point the span to `::<Args>`, not just `<Args>`.
2000 segment.ident.span.shrink_to_hi().to(segment.args.map_or(
2001 segment.ident.span.shrink_to_hi(),
2003 kw::SelfUpper == segment.ident.name,
2014 let suggestion = vec![
2016 // Account for people writing `Self::Variant::<Args>`, where
2017 // `Self` is the enum, and suggest replacing `Self` with the
2018 // appropriate type: `Type::<Args>::Variant`.
2019 (qself.span, format!("{type_name}{snippet}"))
2021 (qself_sugg_span, snippet)
2023 (args_span, String::new()),
2025 err.multipart_suggestion_verbose(
2028 Applicability::MaybeIncorrect,
2031 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
2033 variant_resolution = Some(variant_def.def_id);
2038 // see if we can satisfy using an inherent associated type
2039 for &impl_ in tcx.inherent_impls(adt_def.did()) {
2040 let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, impl_) else {
2043 let ty::Adt(_, adt_substs) = qself_ty.kind() else {
2044 // FIXME(inherent_associated_types)
2045 bug!("unimplemented: non-adt self of inherent assoc ty");
2047 let item_substs = self.create_substs_for_associated_item(
2053 let ty = tcx.bound_type_of(assoc_ty_did).subst(tcx, item_substs);
2054 return Ok((ty, DefKind::AssocTy, assoc_ty_did));
2058 // Find the type of the associated item, and the trait where the associated
2059 // item is declared.
2060 let bound = match (&qself_ty.kind(), qself_res) {
2061 (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
2062 // `Self` in an impl of a trait -- we have a concrete self type and a
2064 let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) else {
2065 // A cycle error occurred, most likely.
2066 let guar = tcx.sess.delay_span_bug(span, "expected cycle error");
2070 self.one_bound_for_assoc_type(
2071 || traits::supertraits(tcx, ty::Binder::dummy(trait_ref.subst_identity())),
2072 || "Self".to_string(),
2080 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
2081 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
2083 let reported = if variant_resolution.is_some() {
2084 // Variant in type position
2085 let msg = format!("expected type, found variant `{}`", assoc_ident);
2086 tcx.sess.span_err(span, &msg)
2087 } else if qself_ty.is_enum() {
2088 let mut err = struct_span_err!(
2092 "no variant named `{}` found for enum `{}`",
2097 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2098 if let Some(suggested_name) = find_best_match_for_name(
2102 .map(|variant| variant.name)
2103 .collect::<Vec<Symbol>>(),
2107 err.span_suggestion(
2109 "there is a variant with a similar name",
2111 Applicability::MaybeIncorrect,
2116 format!("variant not found in `{}`", qself_ty),
2120 if let Some(sp) = tcx.hir().span_if_local(adt_def.did()) {
2121 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2125 } else if let Err(reported) = qself_ty.error_reported() {
2127 } else if let ty::Alias(ty::Opaque, alias_ty) = qself_ty.kind() {
2128 // `<impl Trait as OtherTrait>::Assoc` makes no sense.
2131 tcx.def_span(alias_ty.def_id),
2133 "`impl Trait` is not allowed in path parameters"
2135 .emit() // Already reported in an earlier stage.
2137 let traits: Vec<_> =
2138 self.probe_traits_that_match_assoc_ty(qself_ty, assoc_ident);
2140 // Don't print `TyErr` to the user.
2141 self.report_ambiguous_associated_type(
2143 &[qself_ty.to_string()],
2148 return Err(reported);
2152 let trait_did = bound.def_id();
2153 let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, trait_did) else {
2154 // Assume that if it's not matched, there must be a const defined with the same name
2155 // but it was used in a type position.
2156 let msg = format!("found associated const `{assoc_ident}` when type was expected");
2157 let guar = tcx.sess.struct_span_err(span, &msg).emit();
2161 let ty = self.projected_ty_from_poly_trait_ref(span, assoc_ty_did, assoc_segment, bound);
2163 if let Some(variant_def_id) = variant_resolution {
2164 tcx.struct_span_lint_hir(
2165 AMBIGUOUS_ASSOCIATED_ITEMS,
2168 "ambiguous associated item",
2170 let mut could_refer_to = |kind: DefKind, def_id, also| {
2171 let note_msg = format!(
2172 "`{}` could{} refer to the {} defined here",
2177 lint.span_note(tcx.def_span(def_id), ¬e_msg);
2180 could_refer_to(DefKind::Variant, variant_def_id, "");
2181 could_refer_to(DefKind::AssocTy, assoc_ty_did, " also");
2183 lint.span_suggestion(
2185 "use fully-qualified syntax",
2186 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2187 Applicability::MachineApplicable,
2194 Ok((ty, DefKind::AssocTy, assoc_ty_did))
2197 fn probe_traits_that_match_assoc_ty(
2202 let tcx = self.tcx();
2204 // In contexts that have no inference context, just make a new one.
2205 // We do need a local variable to store it, though.
2207 let infcx = if let Some(infcx) = self.infcx() {
2210 assert!(!qself_ty.needs_infer());
2211 infcx_ = tcx.infer_ctxt().build();
2216 .filter(|trait_def_id| {
2217 // Consider only traits with the associated type
2218 tcx.associated_items(*trait_def_id)
2219 .in_definition_order()
2221 i.kind.namespace() == Namespace::TypeNS
2222 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
2223 && matches!(i.kind, ty::AssocKind::Type)
2225 // Consider only accessible traits
2226 && tcx.visibility(*trait_def_id)
2227 .is_accessible_from(self.item_def_id(), tcx)
2228 && tcx.all_impls(*trait_def_id)
2229 .any(|impl_def_id| {
2230 let trait_ref = tcx.impl_trait_ref(impl_def_id);
2231 trait_ref.map_or(false, |trait_ref| {
2232 let impl_ = trait_ref.subst(
2234 infcx.fresh_substs_for_item(DUMMY_SP, impl_def_id),
2238 ty::ParamEnv::empty(),
2239 tcx.erase_regions(impl_.self_ty()),
2240 tcx.erase_regions(qself_ty),
2244 && tcx.impl_polarity(impl_def_id) != ty::ImplPolarity::Negative
2247 .map(|trait_def_id| tcx.def_path_str(trait_def_id))
2257 ) -> Option<DefId> {
2258 let tcx = self.tcx();
2259 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
2261 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
2262 // of calling `find_by_name_and_kind`.
2263 let item = tcx.associated_items(scope).in_definition_order().find(|i| {
2264 i.kind.namespace() == Namespace::TypeNS
2265 && i.ident(tcx).normalize_to_macros_2_0() == ident
2268 let kind = DefKind::AssocTy;
2269 if !item.visibility(tcx).is_accessible_from(def_scope, tcx) {
2270 let kind = kind.descr(item.def_id);
2271 let msg = format!("{kind} `{ident}` is private");
2272 let def_span = self.tcx().def_span(item.def_id);
2274 .struct_span_err_with_code(span, &msg, rustc_errors::error_code!(E0624))
2275 .span_label(span, &format!("private {kind}"))
2276 .span_label(def_span, &format!("{kind} defined here"))
2279 tcx.check_stability(item.def_id, Some(block), span, None);
2287 opt_self_ty: Option<Ty<'tcx>>,
2289 trait_segment: &hir::PathSegment<'_>,
2290 item_segment: &hir::PathSegment<'_>,
2291 constness: ty::BoundConstness,
2293 let tcx = self.tcx();
2295 let trait_def_id = tcx.parent(item_def_id);
2297 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2299 let Some(self_ty) = opt_self_ty else {
2300 let path_str = tcx.def_path_str(trait_def_id);
2302 let def_id = self.item_def_id();
2304 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2306 let parent_def_id = def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
2307 .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id());
2309 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2311 // If the trait in segment is the same as the trait defining the item,
2312 // use the `<Self as ..>` syntax in the error.
2313 let is_part_of_self_trait_constraints = def_id == trait_def_id;
2314 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2316 let type_names = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2317 vec!["Self".to_string()]
2319 // Find all the types that have an `impl` for the trait.
2320 tcx.all_impls(trait_def_id)
2321 .filter(|impl_def_id| {
2322 // Consider only accessible traits
2323 tcx.visibility(*impl_def_id).is_accessible_from(self.item_def_id(), tcx)
2324 && tcx.impl_polarity(impl_def_id) != ty::ImplPolarity::Negative
2326 .filter_map(|impl_def_id| tcx.impl_trait_ref(impl_def_id))
2327 .map(|impl_| impl_.subst_identity().self_ty())
2328 // We don't care about blanket impls.
2329 .filter(|self_ty| !self_ty.has_non_region_param())
2330 .map(|self_ty| tcx.erase_regions(self_ty).to_string())
2333 // FIXME: also look at `tcx.generics_of(self.item_def_id()).params` any that
2334 // references the trait. Relevant for the first case in
2335 // `src/test/ui/associated-types/associated-types-in-ambiguous-context.rs`
2336 let reported = self.report_ambiguous_associated_type(
2340 item_segment.ident.name,
2342 return tcx.ty_error_with_guaranteed(reported)
2345 debug!("qpath_to_ty: self_type={:?}", self_ty);
2347 let trait_ref = self.ast_path_to_mono_trait_ref(
2356 let item_substs = self.create_substs_for_associated_item(
2363 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2365 tcx.mk_projection(item_def_id, item_substs)
2368 pub fn prohibit_generics<'a>(
2370 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
2371 extend: impl Fn(&mut Diagnostic),
2373 let args = segments.clone().flat_map(|segment| segment.args().args);
2375 let (lt, ty, ct, inf) =
2376 args.clone().fold((false, false, false, false), |(lt, ty, ct, inf), arg| match arg {
2377 hir::GenericArg::Lifetime(_) => (true, ty, ct, inf),
2378 hir::GenericArg::Type(_) => (lt, true, ct, inf),
2379 hir::GenericArg::Const(_) => (lt, ty, true, inf),
2380 hir::GenericArg::Infer(_) => (lt, ty, ct, true),
2382 let mut emitted = false;
2383 if lt || ty || ct || inf {
2384 let types_and_spans: Vec<_> = segments
2386 .flat_map(|segment| {
2387 if segment.args().args.is_empty() {
2392 Res::PrimTy(ty) => format!("{} `{}`", segment.res.descr(), ty.name()),
2394 if let Some(name) = self.tcx().opt_item_name(def_id) => {
2395 format!("{} `{name}`", segment.res.descr())
2397 Res::Err => "this type".to_string(),
2398 _ => segment.res.descr().to_string(),
2405 let this_type = match &types_and_spans[..] {
2406 [.., _, (last, _)] => format!(
2408 types_and_spans[..types_and_spans.len() - 1]
2410 .map(|(x, _)| x.as_str())
2412 .collect::<String>()
2414 [(only, _)] => only.to_string(),
2415 [] => "this type".to_string(),
2418 let arg_spans: Vec<Span> = args.map(|arg| arg.span()).collect();
2420 let mut kinds = Vec::with_capacity(4);
2422 kinds.push("lifetime");
2428 kinds.push("const");
2431 kinds.push("generic");
2433 let (kind, s) = match kinds[..] {
2437 kinds[..kinds.len() - 1]
2441 .collect::<String>()
2445 [only] => (only.to_string(), ""),
2446 [] => unreachable!(),
2448 let last_span = *arg_spans.last().unwrap();
2449 let span: MultiSpan = arg_spans.into();
2450 let mut err = struct_span_err!(
2454 "{kind} arguments are not allowed on {this_type}",
2456 err.span_label(last_span, format!("{kind} argument{s} not allowed"));
2457 for (what, span) in types_and_spans {
2458 err.span_label(span, format!("not allowed on {what}"));
2465 for segment in segments {
2466 // Only emit the first error to avoid overloading the user with error messages.
2467 if let Some(b) = segment.args().bindings.first() {
2468 prohibit_assoc_ty_binding(self.tcx(), b.span);
2475 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2476 pub fn def_ids_for_value_path_segments(
2478 segments: &[hir::PathSegment<'_>],
2479 self_ty: Option<Ty<'tcx>>,
2484 // We need to extract the type parameters supplied by the user in
2485 // the path `path`. Due to the current setup, this is a bit of a
2486 // tricky-process; the problem is that resolve only tells us the
2487 // end-point of the path resolution, and not the intermediate steps.
2488 // Luckily, we can (at least for now) deduce the intermediate steps
2489 // just from the end-point.
2491 // There are basically five cases to consider:
2493 // 1. Reference to a constructor of a struct:
2495 // struct Foo<T>(...)
2497 // In this case, the parameters are declared in the type space.
2499 // 2. Reference to a constructor of an enum variant:
2501 // enum E<T> { Foo(...) }
2503 // In this case, the parameters are defined in the type space,
2504 // but may be specified either on the type or the variant.
2506 // 3. Reference to a fn item or a free constant:
2510 // In this case, the path will again always have the form
2511 // `a::b::foo::<T>` where only the final segment should have
2512 // type parameters. However, in this case, those parameters are
2513 // declared on a value, and hence are in the `FnSpace`.
2515 // 4. Reference to a method or an associated constant:
2517 // impl<A> SomeStruct<A> {
2521 // Here we can have a path like
2522 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2523 // may appear in two places. The penultimate segment,
2524 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2525 // final segment, `foo::<B>` contains parameters in fn space.
2527 // The first step then is to categorize the segments appropriately.
2529 let tcx = self.tcx();
2531 assert!(!segments.is_empty());
2532 let last = segments.len() - 1;
2534 let mut path_segs = vec![];
2537 // Case 1. Reference to a struct constructor.
2538 DefKind::Ctor(CtorOf::Struct, ..) => {
2539 // Everything but the final segment should have no
2540 // parameters at all.
2541 let generics = tcx.generics_of(def_id);
2542 // Variant and struct constructors use the
2543 // generics of their parent type definition.
2544 let generics_def_id = generics.parent.unwrap_or(def_id);
2545 path_segs.push(PathSeg(generics_def_id, last));
2548 // Case 2. Reference to a variant constructor.
2549 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2550 let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2551 let adt_def = self.probe_adt(span, self_ty).unwrap();
2552 debug_assert!(adt_def.is_enum());
2553 (adt_def.did(), last)
2554 } else if last >= 1 && segments[last - 1].args.is_some() {
2555 // Everything but the penultimate segment should have no
2556 // parameters at all.
2557 let mut def_id = def_id;
2559 // `DefKind::Ctor` -> `DefKind::Variant`
2560 if let DefKind::Ctor(..) = kind {
2561 def_id = tcx.parent(def_id);
2564 // `DefKind::Variant` -> `DefKind::Enum`
2565 let enum_def_id = tcx.parent(def_id);
2566 (enum_def_id, last - 1)
2568 // FIXME: lint here recommending `Enum::<...>::Variant` form
2569 // instead of `Enum::Variant::<...>` form.
2571 // Everything but the final segment should have no
2572 // parameters at all.
2573 let generics = tcx.generics_of(def_id);
2574 // Variant and struct constructors use the
2575 // generics of their parent type definition.
2576 (generics.parent.unwrap_or(def_id), last)
2578 path_segs.push(PathSeg(generics_def_id, index));
2581 // Case 3. Reference to a top-level value.
2582 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static(_) => {
2583 path_segs.push(PathSeg(def_id, last));
2586 // Case 4. Reference to a method or associated const.
2587 DefKind::AssocFn | DefKind::AssocConst => {
2588 if segments.len() >= 2 {
2589 let generics = tcx.generics_of(def_id);
2590 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2592 path_segs.push(PathSeg(def_id, last));
2595 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2598 debug!("path_segs = {:?}", path_segs);
2603 /// Check a type `Path` and convert it to a `Ty`.
2606 opt_self_ty: Option<Ty<'tcx>>,
2607 path: &hir::Path<'_>,
2608 permit_variants: bool,
2610 let tcx = self.tcx();
2613 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2614 path.res, opt_self_ty, path.segments
2617 let span = path.span;
2619 Res::Def(DefKind::OpaqueTy | DefKind::ImplTraitPlaceholder, did) => {
2620 // Check for desugared `impl Trait`.
2621 assert!(tcx.is_type_alias_impl_trait(did));
2622 let item_segment = path.segments.split_last().unwrap();
2623 self.prohibit_generics(item_segment.1.iter(), |err| {
2624 err.note("`impl Trait` types can't have type parameters");
2626 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2627 tcx.mk_opaque(did, substs)
2634 | DefKind::ForeignTy,
2637 assert_eq!(opt_self_ty, None);
2638 self.prohibit_generics(path.segments.split_last().unwrap().1.iter(), |_| {});
2639 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2641 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2642 // Convert "variant type" as if it were a real type.
2643 // The resulting `Ty` is type of the variant's enum for now.
2644 assert_eq!(opt_self_ty, None);
2647 self.def_ids_for_value_path_segments(path.segments, None, kind, def_id, span);
2648 let generic_segs: FxHashSet<_> =
2649 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2650 self.prohibit_generics(
2651 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2652 if !generic_segs.contains(&index) { Some(seg) } else { None }
2655 err.note("enum variants can't have type parameters");
2659 let PathSeg(def_id, index) = path_segs.last().unwrap();
2660 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2662 Res::Def(DefKind::TyParam, def_id) => {
2663 assert_eq!(opt_self_ty, None);
2664 self.prohibit_generics(path.segments.iter(), |err| {
2665 if let Some(span) = tcx.def_ident_span(def_id) {
2666 let name = tcx.item_name(def_id);
2667 err.span_note(span, &format!("type parameter `{name}` defined here"));
2671 let def_id = def_id.expect_local();
2672 let item_def_id = tcx.hir().ty_param_owner(def_id);
2673 let generics = tcx.generics_of(item_def_id);
2674 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2675 tcx.mk_ty_param(index, tcx.hir().ty_param_name(def_id))
2677 Res::SelfTyParam { .. } => {
2678 // `Self` in trait or type alias.
2679 assert_eq!(opt_self_ty, None);
2680 self.prohibit_generics(path.segments.iter(), |err| {
2681 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments[..] {
2682 err.span_suggestion_verbose(
2683 ident.span.shrink_to_hi().to(args.span_ext),
2684 "the `Self` type doesn't accept type parameters",
2686 Applicability::MaybeIncorrect,
2690 tcx.types.self_param
2692 Res::SelfTyAlias { alias_to: def_id, forbid_generic, .. } => {
2693 // `Self` in impl (we know the concrete type).
2694 assert_eq!(opt_self_ty, None);
2695 // Try to evaluate any array length constants.
2696 let ty = tcx.at(span).type_of(def_id);
2697 let span_of_impl = tcx.span_of_impl(def_id);
2698 self.prohibit_generics(path.segments.iter(), |err| {
2699 let def_id = match *ty.kind() {
2700 ty::Adt(self_def, _) => self_def.did(),
2704 let type_name = tcx.item_name(def_id);
2705 let span_of_ty = tcx.def_ident_span(def_id);
2706 let generics = tcx.generics_of(def_id).count();
2708 let msg = format!("`Self` is of type `{ty}`");
2709 if let (Ok(i_sp), Some(t_sp)) = (span_of_impl, span_of_ty) {
2710 let mut span: MultiSpan = vec![t_sp].into();
2711 span.push_span_label(
2713 &format!("`Self` is on type `{type_name}` in this `impl`"),
2715 let mut postfix = "";
2717 postfix = ", which doesn't have generic parameters";
2719 span.push_span_label(
2721 &format!("`Self` corresponds to this type{postfix}"),
2723 err.span_note(span, &msg);
2727 for segment in path.segments {
2728 if let Some(args) = segment.args && segment.ident.name == kw::SelfUpper {
2730 // FIXME(estebank): we could also verify that the arguments being
2731 // work for the `enum`, instead of just looking if it takes *any*.
2732 err.span_suggestion_verbose(
2733 segment.ident.span.shrink_to_hi().to(args.span_ext),
2734 "the `Self` type doesn't accept type parameters",
2736 Applicability::MachineApplicable,
2740 err.span_suggestion_verbose(
2743 "the `Self` type doesn't accept type parameters, use the \
2744 concrete type's name `{type_name}` instead if you want to \
2745 specify its type parameters"
2748 Applicability::MaybeIncorrect,
2754 // HACK(min_const_generics): Forbid generic `Self` types
2755 // here as we can't easily do that during nameres.
2757 // We do this before normalization as we otherwise allow
2759 // trait AlwaysApplicable { type Assoc; }
2760 // impl<T: ?Sized> AlwaysApplicable for T { type Assoc = usize; }
2762 // trait BindsParam<T> {
2765 // impl<T> BindsParam<T> for <T as AlwaysApplicable>::Assoc {
2766 // type ArrayTy = [u8; Self::MAX];
2769 // Note that the normalization happens in the param env of
2770 // the anon const, which is empty. This is why the
2771 // `AlwaysApplicable` impl needs a `T: ?Sized` bound for
2772 // this to compile if we were to normalize here.
2773 if forbid_generic && ty.needs_subst() {
2774 let mut err = tcx.sess.struct_span_err(
2776 "generic `Self` types are currently not permitted in anonymous constants",
2778 if let Some(hir::Node::Item(&hir::Item {
2779 kind: hir::ItemKind::Impl(impl_),
2781 })) = tcx.hir().get_if_local(def_id)
2783 err.span_note(impl_.self_ty.span, "not a concrete type");
2785 tcx.ty_error_with_guaranteed(err.emit())
2790 Res::Def(DefKind::AssocTy, def_id) => {
2791 debug_assert!(path.segments.len() >= 2);
2792 self.prohibit_generics(path.segments[..path.segments.len() - 2].iter(), |_| {});
2793 // HACK: until we support `<Type as ~const Trait>`, assume all of them are.
2794 let constness = if tcx.has_attr(tcx.parent(def_id), sym::const_trait) {
2795 ty::BoundConstness::ConstIfConst
2797 ty::BoundConstness::NotConst
2803 &path.segments[path.segments.len() - 2],
2804 path.segments.last().unwrap(),
2808 Res::PrimTy(prim_ty) => {
2809 assert_eq!(opt_self_ty, None);
2810 self.prohibit_generics(path.segments.iter(), |err| {
2811 let name = prim_ty.name_str();
2812 for segment in path.segments {
2813 if let Some(args) = segment.args {
2814 err.span_suggestion_verbose(
2815 segment.ident.span.shrink_to_hi().to(args.span_ext),
2816 &format!("primitive type `{name}` doesn't have generic parameters"),
2818 Applicability::MaybeIncorrect,
2824 hir::PrimTy::Bool => tcx.types.bool,
2825 hir::PrimTy::Char => tcx.types.char,
2826 hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2827 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2828 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2829 hir::PrimTy::Str => tcx.types.str_,
2836 .delay_span_bug(path.span, "path with `Res::Err` but no error emitted");
2837 self.set_tainted_by_errors(e);
2838 self.tcx().ty_error_with_guaranteed(e)
2840 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2844 /// Parses the programmer's textual representation of a type into our
2845 /// internal notion of a type.
2846 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2847 self.ast_ty_to_ty_inner(ast_ty, false, false)
2850 /// Parses the programmer's textual representation of a type into our
2851 /// internal notion of a type. This is meant to be used within a path.
2852 pub fn ast_ty_to_ty_in_path(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2853 self.ast_ty_to_ty_inner(ast_ty, false, true)
2856 /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2857 /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2858 #[instrument(level = "debug", skip(self), ret)]
2859 fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool, in_path: bool) -> Ty<'tcx> {
2860 let tcx = self.tcx();
2862 let result_ty = match &ast_ty.kind {
2863 hir::TyKind::Slice(ty) => tcx.mk_slice(self.ast_ty_to_ty(ty)),
2864 hir::TyKind::Ptr(mt) => {
2865 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl })
2867 hir::TyKind::Ref(region, mt) => {
2868 let r = self.ast_region_to_region(region, None);
2870 let t = self.ast_ty_to_ty_inner(mt.ty, true, false);
2871 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2873 hir::TyKind::Never => tcx.types.never,
2874 hir::TyKind::Tup(fields) => tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(t))),
2875 hir::TyKind::BareFn(bf) => {
2876 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span);
2878 tcx.mk_fn_ptr(self.ty_of_fn(
2887 hir::TyKind::TraitObject(bounds, lifetime, repr) => {
2888 self.maybe_lint_bare_trait(ast_ty, in_path);
2889 let repr = match repr {
2890 TraitObjectSyntax::Dyn | TraitObjectSyntax::None => ty::Dyn,
2891 TraitObjectSyntax::DynStar => ty::DynStar,
2893 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed, repr)
2895 hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2896 debug!(?maybe_qself, ?path);
2897 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2898 self.res_to_ty(opt_self_ty, path, false)
2900 &hir::TyKind::OpaqueDef(item_id, lifetimes, in_trait) => {
2901 let opaque_ty = tcx.hir().item(item_id);
2902 let def_id = item_id.owner_id.to_def_id();
2904 match opaque_ty.kind {
2905 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
2906 self.impl_trait_ty_to_ty(def_id, lifetimes, origin, in_trait)
2908 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2911 hir::TyKind::Path(hir::QPath::TypeRelative(qself, segment)) => {
2912 debug!(?qself, ?segment);
2913 let ty = self.ast_ty_to_ty_inner(qself, false, true);
2914 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, qself, segment, false)
2915 .map(|(ty, _, _)| ty)
2916 .unwrap_or_else(|_| tcx.ty_error())
2918 &hir::TyKind::Path(hir::QPath::LangItem(lang_item, span, _)) => {
2919 let def_id = tcx.require_lang_item(lang_item, Some(span));
2920 let (substs, _) = self.create_substs_for_ast_path(
2924 &hir::PathSegment::invalid(),
2925 &GenericArgs::none(),
2928 ty::BoundConstness::NotConst,
2930 EarlyBinder(tcx.at(span).type_of(def_id)).subst(tcx, substs)
2932 hir::TyKind::Array(ty, length) => {
2933 let length = match length {
2934 &hir::ArrayLen::Infer(_, span) => self.ct_infer(tcx.types.usize, None, span),
2935 hir::ArrayLen::Body(constant) => {
2936 ty::Const::from_anon_const(tcx, constant.def_id)
2940 tcx.mk_ty(ty::Array(self.ast_ty_to_ty(ty), length))
2942 hir::TyKind::Typeof(e) => {
2943 let ty_erased = tcx.type_of(e.def_id);
2944 let ty = tcx.fold_regions(ty_erased, |r, _| {
2945 if r.is_erased() { tcx.lifetimes.re_static } else { r }
2947 let span = ast_ty.span;
2948 tcx.sess.emit_err(TypeofReservedKeywordUsed {
2951 opt_sugg: Some((span, Applicability::MachineApplicable))
2952 .filter(|_| ty.is_suggestable(tcx, false)),
2957 hir::TyKind::Infer => {
2958 // Infer also appears as the type of arguments or return
2959 // values in an ExprKind::Closure, or as
2960 // the type of local variables. Both of these cases are
2961 // handled specially and will not descend into this routine.
2962 self.ty_infer(None, ast_ty.span)
2964 hir::TyKind::Err => tcx.ty_error(),
2967 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2971 #[instrument(level = "debug", skip(self), ret)]
2972 fn impl_trait_ty_to_ty(
2975 lifetimes: &[hir::GenericArg<'_>],
2976 origin: OpaqueTyOrigin,
2979 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2980 let tcx = self.tcx();
2982 let generics = tcx.generics_of(def_id);
2984 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2985 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2986 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2987 // Our own parameters are the resolved lifetimes.
2988 let GenericParamDefKind::Lifetime { .. } = param.kind else { bug!() };
2989 let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] else { bug!() };
2990 self.ast_region_to_region(lifetime, None).into()
2992 tcx.mk_param_from_def(param)
2995 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2997 if in_trait { tcx.mk_projection(def_id, substs) } else { tcx.mk_opaque(def_id, substs) }
3000 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
3002 hir::TyKind::Infer if expected_ty.is_some() => {
3003 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
3004 expected_ty.unwrap()
3006 _ => self.ast_ty_to_ty(ty),
3010 #[instrument(level = "debug", skip(self, hir_id, unsafety, abi, decl, generics, hir_ty), ret)]
3014 unsafety: hir::Unsafety,
3016 decl: &hir::FnDecl<'_>,
3017 generics: Option<&hir::Generics<'_>>,
3018 hir_ty: Option<&hir::Ty<'_>>,
3019 ) -> ty::PolyFnSig<'tcx> {
3020 let tcx = self.tcx();
3021 let bound_vars = tcx.late_bound_vars(hir_id);
3022 debug!(?bound_vars);
3024 // We proactively collect all the inferred type params to emit a single error per fn def.
3025 let mut visitor = HirPlaceholderCollector::default();
3026 let mut infer_replacements = vec![];
3028 if let Some(generics) = generics {
3029 walk_generics(&mut visitor, generics);
3032 let input_tys: Vec<_> = decl
3037 if let hir::TyKind::Infer = a.kind && !self.allow_ty_infer() {
3038 if let Some(suggested_ty) =
3039 self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i))
3041 infer_replacements.push((a.span, suggested_ty.to_string()));
3042 return suggested_ty;
3046 // Only visit the type looking for `_` if we didn't fix the type above
3047 visitor.visit_ty(a);
3048 self.ty_of_arg(a, None)
3052 let output_ty = match decl.output {
3053 hir::FnRetTy::Return(output) => {
3054 if let hir::TyKind::Infer = output.kind
3055 && !self.allow_ty_infer()
3056 && let Some(suggested_ty) =
3057 self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, None)
3059 infer_replacements.push((output.span, suggested_ty.to_string()));
3062 visitor.visit_ty(output);
3063 self.ast_ty_to_ty(output)
3066 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
3071 let fn_ty = tcx.mk_fn_sig(input_tys.into_iter(), output_ty, decl.c_variadic, unsafety, abi);
3072 let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3074 if !self.allow_ty_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) {
3075 // We always collect the spans for placeholder types when evaluating `fn`s, but we
3076 // only want to emit an error complaining about them if infer types (`_`) are not
3077 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
3078 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
3080 let mut diag = crate::collect::placeholder_type_error_diag(
3084 infer_replacements.iter().map(|(s, _)| *s).collect(),
3090 if !infer_replacements.is_empty() {
3091 diag.multipart_suggestion(
3093 "try replacing `_` with the type{} in the corresponding trait method signature",
3094 rustc_errors::pluralize!(infer_replacements.len()),
3097 Applicability::MachineApplicable,
3104 // Find any late-bound regions declared in return type that do
3105 // not appear in the arguments. These are not well-formed.
3108 // for<'a> fn() -> &'a str <-- 'a is bad
3109 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
3110 let inputs = bare_fn_ty.inputs();
3111 let late_bound_in_args =
3112 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
3113 let output = bare_fn_ty.output();
3114 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
3116 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3121 "return type references {}, which is not constrained by the fn input types",
3129 /// Given a fn_hir_id for a impl function, suggest the type that is found on the
3130 /// corresponding function in the trait that the impl implements, if it exists.
3131 /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
3132 /// corresponds to the return type.
3133 fn suggest_trait_fn_ty_for_impl_fn_infer(
3135 fn_hir_id: hir::HirId,
3136 arg_idx: Option<usize>,
3137 ) -> Option<Ty<'tcx>> {
3138 let tcx = self.tcx();
3139 let hir = tcx.hir();
3141 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3142 hir.get(fn_hir_id) else { return None };
3143 let i = hir.get_parent(fn_hir_id).expect_item().expect_impl();
3145 let trait_ref = self.instantiate_mono_trait_ref(
3146 i.of_trait.as_ref()?,
3147 self.ast_ty_to_ty(i.self_ty),
3148 ty::BoundConstness::NotConst,
3151 let assoc = tcx.associated_items(trait_ref.def_id).find_by_name_and_kind(
3158 let fn_sig = tcx.fn_sig(assoc.def_id).subst(
3160 trait_ref.substs.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3163 let ty = if let Some(arg_idx) = arg_idx { fn_sig.input(arg_idx) } else { fn_sig.output() };
3165 Some(tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), ty))
3168 #[instrument(level = "trace", skip(self, generate_err))]
3169 fn validate_late_bound_regions(
3171 constrained_regions: FxHashSet<ty::BoundRegionKind>,
3172 referenced_regions: FxHashSet<ty::BoundRegionKind>,
3173 generate_err: impl Fn(&str) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
3175 for br in referenced_regions.difference(&constrained_regions) {
3176 let br_name = match *br {
3177 ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) | ty::BrEnv => {
3178 "an anonymous lifetime".to_string()
3180 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
3183 let mut err = generate_err(&br_name);
3185 if let ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) = *br {
3186 // The only way for an anonymous lifetime to wind up
3187 // in the return type but **also** be unconstrained is
3188 // if it only appears in "associated types" in the
3189 // input. See #47511 and #62200 for examples. In this case,
3190 // though we can easily give a hint that ought to be
3193 "lifetimes appearing in an associated or opaque type are not considered constrained",
3195 err.note("consider introducing a named lifetime parameter");
3202 /// Given the bounds on an object, determines what single region bound (if any) we can
3203 /// use to summarize this type. The basic idea is that we will use the bound the user
3204 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
3205 /// for region bounds. It may be that we can derive no bound at all, in which case
3206 /// we return `None`.
3207 fn compute_object_lifetime_bound(
3210 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3211 ) -> Option<ty::Region<'tcx>> // if None, use the default
3213 let tcx = self.tcx();
3215 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
3217 // No explicit region bound specified. Therefore, examine trait
3218 // bounds and see if we can derive region bounds from those.
3219 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3221 // If there are no derived region bounds, then report back that we
3222 // can find no region bound. The caller will use the default.
3223 if derived_region_bounds.is_empty() {
3227 // If any of the derived region bounds are 'static, that is always
3229 if derived_region_bounds.iter().any(|r| r.is_static()) {
3230 return Some(tcx.lifetimes.re_static);
3233 // Determine whether there is exactly one unique region in the set
3234 // of derived region bounds. If so, use that. Otherwise, report an
3236 let r = derived_region_bounds[0];
3237 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3238 tcx.sess.emit_err(AmbiguousLifetimeBound { span });
3243 /// Make sure that we are in the condition to suggest the blanket implementation.
3244 fn maybe_lint_blanket_trait_impl(&self, self_ty: &hir::Ty<'_>, diag: &mut Diagnostic) {
3245 let tcx = self.tcx();
3246 let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
3247 if let hir::Node::Item(hir::Item {
3249 hir::ItemKind::Impl(hir::Impl {
3250 self_ty: impl_self_ty, of_trait: Some(of_trait_ref), generics, ..
3253 }) = tcx.hir().get_by_def_id(parent_id) && self_ty.hir_id == impl_self_ty.hir_id
3255 if !of_trait_ref.trait_def_id().map_or(false, |def_id| def_id.is_local()) {
3258 let of_trait_span = of_trait_ref.path.span;
3259 // make sure that we are not calling unwrap to abort during the compilation
3260 let Ok(impl_trait_name) = tcx.sess.source_map().span_to_snippet(self_ty.span) else { return; };
3261 let Ok(of_trait_name) = tcx.sess.source_map().span_to_snippet(of_trait_span) else { return; };
3262 // check if the trait has generics, to make a correct suggestion
3263 let param_name = generics.params.next_type_param_name(None);
3265 let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() {
3266 (span, format!(", {}: {}", param_name, impl_trait_name))
3268 (generics.span, format!("<{}: {}>", param_name, impl_trait_name))
3270 diag.multipart_suggestion(
3271 format!("alternatively use a blanket \
3272 implementation to implement `{of_trait_name}` for \
3273 all types that also implement `{impl_trait_name}`"),
3275 (self_ty.span, param_name),
3278 Applicability::MaybeIncorrect,
3283 fn maybe_lint_bare_trait(&self, self_ty: &hir::Ty<'_>, in_path: bool) {
3284 let tcx = self.tcx();
3285 if let hir::TyKind::TraitObject([poly_trait_ref, ..], _, TraitObjectSyntax::None) =
3288 let needs_bracket = in_path
3292 .span_to_prev_source(self_ty.span)
3294 .map_or(false, |s| s.trim_end().ends_with('<'));
3296 let is_global = poly_trait_ref.trait_ref.path.is_global();
3298 let mut sugg = Vec::from_iter([(
3299 self_ty.span.shrink_to_lo(),
3302 if needs_bracket { "<" } else { "" },
3303 if is_global { "(" } else { "" },
3307 if is_global || needs_bracket {
3309 self_ty.span.shrink_to_hi(),
3312 if is_global { ")" } else { "" },
3313 if needs_bracket { ">" } else { "" },
3318 if self_ty.span.edition() >= Edition::Edition2021 {
3319 let msg = "trait objects must include the `dyn` keyword";
3320 let label = "add `dyn` keyword before this trait";
3322 rustc_errors::struct_span_err!(tcx.sess, self_ty.span, E0782, "{}", msg);
3323 if self_ty.span.can_be_used_for_suggestions() {
3324 diag.multipart_suggestion_verbose(
3327 Applicability::MachineApplicable,
3330 // check if the impl trait that we are considering is a impl of a local trait
3331 self.maybe_lint_blanket_trait_impl(&self_ty, &mut diag);
3334 let msg = "trait objects without an explicit `dyn` are deprecated";
3335 tcx.struct_span_lint_hir(
3341 lint.multipart_suggestion_verbose(
3344 Applicability::MachineApplicable,
3346 self.maybe_lint_blanket_trait_impl(&self_ty, lint);