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::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};
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<'a>(&'a 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>
137 struct ConvertedBinding<'a, 'tcx> {
140 kind: ConvertedBindingKind<'a, 'tcx>,
141 gen_args: &'a GenericArgs<'a>,
146 enum ConvertedBindingKind<'a, 'tcx> {
147 Equality(ty::Term<'tcx>),
148 Constraint(&'a [hir::GenericBound<'a>]),
151 /// New-typed boolean indicating whether explicit late-bound lifetimes
152 /// are present in a set of generic arguments.
154 /// For example if we have some method `fn f<'a>(&'a self)` implemented
155 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
156 /// is late-bound so should not be provided explicitly. Thus, if `f` is
157 /// instantiated with some generic arguments providing `'a` explicitly,
158 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
159 /// can provide an appropriate diagnostic later.
160 #[derive(Copy, Clone, PartialEq, Debug)]
161 pub enum ExplicitLateBound {
166 #[derive(Copy, Clone, PartialEq)]
167 pub enum IsMethodCall {
172 /// Denotes the "position" of a generic argument, indicating if it is a generic type,
173 /// generic function or generic method call.
174 #[derive(Copy, Clone, PartialEq)]
175 pub(crate) enum GenericArgPosition {
177 Value, // e.g., functions
181 /// A marker denoting that the generic arguments that were
182 /// provided did not match the respective generic parameters.
183 #[derive(Clone, Default, Debug)]
184 pub struct GenericArgCountMismatch {
185 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
186 pub reported: Option<ErrorGuaranteed>,
187 /// A list of spans of arguments provided that were not valid.
188 pub invalid_args: Vec<Span>,
191 /// Decorates the result of a generic argument count mismatch
192 /// check with whether explicit late bounds were provided.
193 #[derive(Clone, Debug)]
194 pub struct GenericArgCountResult {
195 pub explicit_late_bound: ExplicitLateBound,
196 pub correct: Result<(), GenericArgCountMismatch>,
199 pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> {
200 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
204 param: &ty::GenericParamDef,
205 arg: &GenericArg<'_>,
206 ) -> subst::GenericArg<'tcx>;
210 substs: Option<&[subst::GenericArg<'tcx>]>,
211 param: &ty::GenericParamDef,
213 ) -> subst::GenericArg<'tcx>;
216 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
217 #[instrument(level = "debug", skip(self), ret)]
218 pub fn ast_region_to_region(
220 lifetime: &hir::Lifetime,
221 def: Option<&ty::GenericParamDef>,
222 ) -> ty::Region<'tcx> {
223 let tcx = self.tcx();
224 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
226 match tcx.named_region(lifetime.hir_id) {
227 Some(rl::Region::Static) => tcx.lifetimes.re_static,
229 Some(rl::Region::LateBound(debruijn, index, def_id)) => {
230 let name = lifetime_name(def_id.expect_local());
231 let br = ty::BoundRegion {
232 var: ty::BoundVar::from_u32(index),
233 kind: ty::BrNamed(def_id, name),
235 tcx.mk_region(ty::ReLateBound(debruijn, br))
238 Some(rl::Region::EarlyBound(def_id)) => {
239 let name = tcx.hir().ty_param_name(def_id.expect_local());
240 let item_def_id = tcx.hir().ty_param_owner(def_id.expect_local());
241 let generics = tcx.generics_of(item_def_id);
242 let index = generics.param_def_id_to_index[&def_id];
243 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, index, name }))
246 Some(rl::Region::Free(scope, id)) => {
247 let name = lifetime_name(id.expect_local());
248 tcx.mk_region(ty::ReFree(ty::FreeRegion {
250 bound_region: ty::BrNamed(id, name),
253 // (*) -- not late-bound, won't change
257 self.re_infer(def, lifetime.ident.span).unwrap_or_else(|| {
258 debug!(?lifetime, "unelided lifetime in signature");
260 // This indicates an illegal lifetime
261 // elision. `resolve_lifetime` should have
262 // reported an error in this case -- but if
263 // not, let's error out.
264 tcx.sess.delay_span_bug(lifetime.ident.span, "unelided lifetime in signature");
266 // Supply some dummy value. We don't have an
267 // `re_error`, annoyingly, so use `'static`.
268 tcx.lifetimes.re_static
274 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
275 /// returns an appropriate set of substitutions for this particular reference to `I`.
276 pub fn ast_path_substs_for_ty(
280 item_segment: &hir::PathSegment<'_>,
281 ) -> SubstsRef<'tcx> {
282 let (substs, _) = self.create_substs_for_ast_path(
288 item_segment.infer_args,
290 ty::BoundConstness::NotConst,
292 if let Some(b) = item_segment.args().bindings.first() {
293 prohibit_assoc_ty_binding(self.tcx(), b.span);
299 /// Given the type/lifetime/const arguments provided to some path (along with
300 /// an implicit `Self`, if this is a trait reference), returns the complete
301 /// set of substitutions. This may involve applying defaulted type parameters.
302 /// Constraints on associated types are created from `create_assoc_bindings_for_generic_args`.
306 /// ```ignore (illustrative)
307 /// T: std::ops::Index<usize, Output = u32>
308 /// // ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
311 /// 1. The `self_ty` here would refer to the type `T`.
312 /// 2. The path in question is the path to the trait `std::ops::Index`,
313 /// which will have been resolved to a `def_id`
314 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
315 /// parameters are returned in the `SubstsRef`, the associated type bindings like
316 /// `Output = u32` are returned from `create_assoc_bindings_for_generic_args`.
318 /// Note that the type listing given here is *exactly* what the user provided.
320 /// For (generic) associated types
322 /// ```ignore (illustrative)
323 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
326 /// We have the parent substs are the substs for the parent trait:
327 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
328 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
329 /// lists: `[Vec<u8>, u8, 'a]`.
330 #[instrument(level = "debug", skip(self, span), ret)]
331 fn create_substs_for_ast_path<'a>(
335 parent_substs: &[subst::GenericArg<'tcx>],
336 seg: &hir::PathSegment<'_>,
337 generic_args: &'a hir::GenericArgs<'_>,
339 self_ty: Option<Ty<'tcx>>,
340 constness: ty::BoundConstness,
341 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
342 // If the type is parameterized by this region, then replace this
343 // region with the current anon region binding (in other words,
344 // whatever & would get replaced with).
346 let tcx = self.tcx();
347 let generics = tcx.generics_of(def_id);
348 debug!("generics: {:?}", generics);
350 if generics.has_self {
351 if generics.parent.is_some() {
352 // The parent is a trait so it should have at least one subst
353 // for the `Self` type.
354 assert!(!parent_substs.is_empty())
356 // This item (presumably a trait) needs a self-type.
357 assert!(self_ty.is_some());
360 assert!(self_ty.is_none());
363 let arg_count = check_generic_arg_count(
370 GenericArgPosition::Type,
375 // Skip processing if type has no generic parameters.
376 // Traits always have `Self` as a generic parameter, which means they will not return early
377 // here and so associated type bindings will be handled regardless of whether there are any
378 // non-`Self` generic parameters.
379 if generics.params.is_empty() {
380 return (tcx.intern_substs(parent_substs), arg_count);
383 struct SubstsForAstPathCtxt<'a, 'tcx> {
384 astconv: &'a (dyn AstConv<'tcx> + 'a),
386 generic_args: &'a GenericArgs<'a>,
388 inferred_params: Vec<Span>,
392 impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> {
393 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) {
394 if did == self.def_id {
395 (Some(self.generic_args), self.infer_args)
397 // The last component of this tuple is unimportant.
404 param: &ty::GenericParamDef,
405 arg: &GenericArg<'_>,
406 ) -> subst::GenericArg<'tcx> {
407 let tcx = self.astconv.tcx();
409 let mut handle_ty_args = |has_default, ty: &hir::Ty<'_>| {
411 tcx.check_optional_stability(
418 // Default generic parameters may not be marked
419 // with stability attributes, i.e. when the
420 // default parameter was defined at the same time
421 // as the rest of the type. As such, we ignore missing
422 // stability attributes.
426 if let (hir::TyKind::Infer, false) = (&ty.kind, self.astconv.allow_ty_infer()) {
427 self.inferred_params.push(ty.span);
428 tcx.ty_error().into()
430 self.astconv.ast_ty_to_ty(ty).into()
434 match (¶m.kind, arg) {
435 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
436 self.astconv.ast_region_to_region(lt, Some(param)).into()
438 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
439 handle_ty_args(has_default, ty)
441 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
442 handle_ty_args(has_default, &inf.to_ty())
444 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
445 ty::Const::from_opt_const_arg_anon_const(
447 ty::WithOptConstParam {
448 did: ct.value.def_id,
449 const_param_did: Some(param.def_id),
454 (&GenericParamDefKind::Const { .. }, hir::GenericArg::Infer(inf)) => {
455 let ty = tcx.at(self.span).type_of(param.def_id);
456 if self.astconv.allow_ty_infer() {
457 self.astconv.ct_infer(ty, Some(param), inf.span).into()
459 self.inferred_params.push(inf.span);
460 tcx.const_error(ty).into()
469 substs: Option<&[subst::GenericArg<'tcx>]>,
470 param: &ty::GenericParamDef,
472 ) -> subst::GenericArg<'tcx> {
473 let tcx = self.astconv.tcx();
475 GenericParamDefKind::Lifetime => self
477 .re_infer(Some(param), self.span)
479 debug!(?param, "unelided lifetime in signature");
481 // This indicates an illegal lifetime in a non-assoc-trait position
482 tcx.sess.delay_span_bug(self.span, "unelided lifetime in signature");
484 // Supply some dummy value. We don't have an
485 // `re_error`, annoyingly, so use `'static`.
486 tcx.lifetimes.re_static
489 GenericParamDefKind::Type { has_default, .. } => {
490 if !infer_args && has_default {
491 // No type parameter provided, but a default exists.
492 let substs = substs.unwrap();
493 if substs.iter().any(|arg| match arg.unpack() {
494 GenericArgKind::Type(ty) => ty.references_error(),
497 // Avoid ICE #86756 when type error recovery goes awry.
498 return tcx.ty_error().into();
500 tcx.at(self.span).bound_type_of(param.def_id).subst(tcx, substs).into()
501 } else if infer_args {
502 self.astconv.ty_infer(Some(param), self.span).into()
504 // We've already errored above about the mismatch.
505 tcx.ty_error().into()
508 GenericParamDefKind::Const { has_default } => {
509 let ty = tcx.at(self.span).type_of(param.def_id);
510 if ty.references_error() {
511 return tcx.const_error(ty).into();
513 if !infer_args && has_default {
514 tcx.const_param_default(param.def_id).subst(tcx, substs.unwrap()).into()
517 self.astconv.ct_infer(ty, Some(param), self.span).into()
519 // We've already errored above about the mismatch.
520 tcx.const_error(ty).into()
528 let mut substs_ctx = SubstsForAstPathCtxt {
533 inferred_params: vec![],
536 let substs = create_substs_for_generic_args(
546 if let ty::BoundConstness::ConstIfConst = constness
547 && generics.has_self && !tcx.has_attr(def_id, sym::const_trait)
549 tcx.sess.emit_err(crate::errors::ConstBoundForNonConstTrait { span } );
555 fn create_assoc_bindings_for_generic_args<'a>(
557 generic_args: &'a hir::GenericArgs<'_>,
558 ) -> Vec<ConvertedBinding<'a, 'tcx>> {
559 // Convert associated-type bindings or constraints into a separate vector.
560 // Example: Given this:
562 // T: Iterator<Item = u32>
564 // The `T` is passed in as a self-type; the `Item = u32` is
565 // not a "type parameter" of the `Iterator` trait, but rather
566 // a restriction on `<T as Iterator>::Item`, so it is passed
568 let assoc_bindings = generic_args
572 let kind = match &binding.kind {
573 hir::TypeBindingKind::Equality { term } => match term {
574 hir::Term::Ty(ty) => {
575 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty).into())
577 hir::Term::Const(c) => {
578 let c = Const::from_anon_const(self.tcx(), c.def_id);
579 ConvertedBindingKind::Equality(c.into())
582 hir::TypeBindingKind::Constraint { bounds } => {
583 ConvertedBindingKind::Constraint(bounds)
587 hir_id: binding.hir_id,
588 item_name: binding.ident,
590 gen_args: binding.gen_args,
599 pub fn create_substs_for_associated_item(
603 item_segment: &hir::PathSegment<'_>,
604 parent_substs: SubstsRef<'tcx>,
605 ) -> SubstsRef<'tcx> {
607 "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}",
608 span, item_def_id, item_segment
610 let (args, _) = self.create_substs_for_ast_path(
616 item_segment.infer_args,
618 ty::BoundConstness::NotConst,
621 if let Some(b) = item_segment.args().bindings.first() {
622 prohibit_assoc_ty_binding(self.tcx(), b.span);
628 /// Instantiates the path for the given trait reference, assuming that it's
629 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
630 /// The type _cannot_ be a type other than a trait type.
632 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
633 /// are disallowed. Otherwise, they are pushed onto the vector given.
634 pub fn instantiate_mono_trait_ref(
636 trait_ref: &hir::TraitRef<'_>,
638 constness: ty::BoundConstness,
639 ) -> ty::TraitRef<'tcx> {
640 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
642 self.ast_path_to_mono_trait_ref(
644 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
646 trait_ref.path.segments.last().unwrap(),
652 fn instantiate_poly_trait_ref_inner(
656 binding_span: Option<Span>,
657 constness: ty::BoundConstness,
658 bounds: &mut Bounds<'tcx>,
660 trait_ref_span: Span,
662 trait_segment: &hir::PathSegment<'_>,
663 args: &GenericArgs<'_>,
666 ) -> GenericArgCountResult {
667 let (substs, arg_count) = self.create_substs_for_ast_path(
678 let tcx = self.tcx();
679 let bound_vars = tcx.late_bound_vars(hir_id);
682 let assoc_bindings = self.create_assoc_bindings_for_generic_args(args);
685 ty::Binder::bind_with_vars(tcx.mk_trait_ref(trait_def_id, substs), bound_vars);
687 debug!(?poly_trait_ref, ?assoc_bindings);
688 bounds.push_trait_bound(tcx, poly_trait_ref, span, constness);
690 let mut dup_bindings = FxHashMap::default();
691 for binding in &assoc_bindings {
692 // Specify type to assert that error was already reported in `Err` case.
693 let _: Result<_, ErrorGuaranteed> = self.add_predicates_for_ast_type_binding(
700 binding_span.unwrap_or(binding.span),
703 // Okay to ignore `Err` because of `ErrorGuaranteed` (see above).
709 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
710 /// a full trait reference. The resulting trait reference is returned. This may also generate
711 /// auxiliary bounds, which are added to `bounds`.
715 /// ```ignore (illustrative)
716 /// poly_trait_ref = Iterator<Item = u32>
720 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
722 /// **A note on binders:** against our usual convention, there is an implied bounder around
723 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
724 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
725 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
726 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
728 #[instrument(level = "debug", skip(self, span, constness, bounds, speculative))]
729 pub(crate) fn instantiate_poly_trait_ref(
731 trait_ref: &hir::TraitRef<'_>,
733 constness: ty::BoundConstness,
735 bounds: &mut Bounds<'tcx>,
737 ) -> GenericArgCountResult {
738 let hir_id = trait_ref.hir_ref_id;
739 let binding_span = None;
740 let trait_ref_span = trait_ref.path.span;
741 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
742 let trait_segment = trait_ref.path.segments.last().unwrap();
743 let args = trait_segment.args();
744 let infer_args = trait_segment.infer_args;
746 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
747 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, false);
749 self.instantiate_poly_trait_ref_inner(
765 pub(crate) fn instantiate_lang_item_trait_ref(
767 lang_item: hir::LangItem,
770 args: &GenericArgs<'_>,
772 bounds: &mut Bounds<'tcx>,
774 let binding_span = Some(span);
775 let constness = ty::BoundConstness::NotConst;
776 let speculative = false;
777 let trait_ref_span = span;
778 let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
779 let trait_segment = &hir::PathSegment::invalid();
780 let infer_args = false;
782 self.instantiate_poly_trait_ref_inner(
798 fn ast_path_to_mono_trait_ref(
803 trait_segment: &hir::PathSegment<'_>,
805 constness: ty::BoundConstness,
806 ) -> ty::TraitRef<'tcx> {
807 let (substs, _) = self.create_substs_for_ast_trait_ref(
815 if let Some(b) = trait_segment.args().bindings.first() {
816 prohibit_assoc_ty_binding(self.tcx(), b.span);
818 self.tcx().mk_trait_ref(trait_def_id, substs)
821 #[instrument(level = "debug", skip(self, span))]
822 fn create_substs_for_ast_trait_ref<'a>(
827 trait_segment: &'a hir::PathSegment<'a>,
829 constness: ty::BoundConstness,
830 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
831 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
833 self.create_substs_for_ast_path(
838 trait_segment.args(),
839 trait_segment.infer_args,
845 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
847 .associated_items(trait_def_id)
848 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
851 fn trait_defines_associated_const_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
853 .associated_items(trait_def_id)
854 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Const, trait_def_id)
858 /// Sets `implicitly_sized` to true on `Bounds` if necessary
859 pub(crate) fn add_implicitly_sized(
861 bounds: &mut Bounds<'tcx>,
863 ast_bounds: &'tcx [hir::GenericBound<'tcx>],
864 self_ty_where_predicates: Option<(LocalDefId, &'tcx [hir::WherePredicate<'tcx>])>,
867 let tcx = self.tcx();
869 // Try to find an unbound in bounds.
870 let mut unbound = None;
871 let mut search_bounds = |ast_bounds: &'tcx [hir::GenericBound<'tcx>]| {
872 for ab in ast_bounds {
873 if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab {
874 if unbound.is_none() {
875 unbound = Some(&ptr.trait_ref);
877 tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span });
882 search_bounds(ast_bounds);
883 if let Some((self_ty, where_clause)) = self_ty_where_predicates {
884 for clause in where_clause {
885 if let hir::WherePredicate::BoundPredicate(pred) = clause {
886 if pred.is_param_bound(self_ty.to_def_id()) {
887 search_bounds(pred.bounds);
893 let sized_def_id = tcx.lang_items().sized_trait();
894 match (&sized_def_id, unbound) {
895 (Some(sized_def_id), Some(tpb))
896 if tpb.path.res == Res::Def(DefKind::Trait, *sized_def_id) =>
898 // There was in fact a `?Sized` bound, return without doing anything
902 // There was a `?Trait` bound, but it was not `?Sized`; warn.
905 "default bound relaxed for a type parameter, but \
906 this does nothing because the given bound is not \
907 a default; only `?Sized` is supported",
909 // Otherwise, add implicitly sized if `Sized` is available.
912 // There was no `?Sized` bound; add implicitly sized if `Sized` is available.
915 if sized_def_id.is_none() {
916 // No lang item for `Sized`, so we can't add it as a bound.
919 bounds.push_sized(tcx, self_ty, span);
922 /// This helper takes a *converted* parameter type (`param_ty`)
923 /// and an *unconverted* list of bounds:
927 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
929 /// `param_ty`, in ty form
932 /// It adds these `ast_bounds` into the `bounds` structure.
934 /// **A note on binders:** there is an implied binder around
935 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
936 /// for more details.
937 #[instrument(level = "debug", skip(self, ast_bounds, bounds))]
938 pub(crate) fn add_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'hir>>>(
942 bounds: &mut Bounds<'tcx>,
943 bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
945 for ast_bound in ast_bounds {
947 hir::GenericBound::Trait(poly_trait_ref, modifier) => {
948 let constness = match modifier {
949 hir::TraitBoundModifier::MaybeConst => ty::BoundConstness::ConstIfConst,
950 hir::TraitBoundModifier::None => ty::BoundConstness::NotConst,
951 hir::TraitBoundModifier::Maybe => continue,
954 let _ = self.instantiate_poly_trait_ref(
955 &poly_trait_ref.trait_ref,
963 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
964 self.instantiate_lang_item_trait_ref(
965 lang_item, span, hir_id, args, param_ty, bounds,
968 hir::GenericBound::Outlives(lifetime) => {
969 let region = self.ast_region_to_region(lifetime, None);
970 bounds.push_region_bound(
972 ty::Binder::bind_with_vars(
973 ty::OutlivesPredicate(param_ty, region),
983 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
984 /// The self-type for the bounds is given by `param_ty`.
988 /// ```ignore (illustrative)
989 /// fn foo<T: Bar + Baz>() { }
990 /// // ^ ^^^^^^^^^ ast_bounds
994 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
995 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
996 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
998 /// `span` should be the declaration size of the parameter.
999 pub(crate) fn compute_bounds(
1002 ast_bounds: &[hir::GenericBound<'_>],
1004 self.compute_bounds_inner(param_ty, ast_bounds)
1007 /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type
1008 /// named `assoc_name` into ty::Bounds. Ignore the rest.
1009 pub(crate) fn compute_bounds_that_match_assoc_type(
1012 ast_bounds: &[hir::GenericBound<'_>],
1015 let mut result = Vec::new();
1017 for ast_bound in ast_bounds {
1018 if let Some(trait_ref) = ast_bound.trait_ref()
1019 && let Some(trait_did) = trait_ref.trait_def_id()
1020 && self.tcx().trait_may_define_assoc_type(trait_did, assoc_name)
1022 result.push(ast_bound.clone());
1026 self.compute_bounds_inner(param_ty, &result)
1029 fn compute_bounds_inner(
1032 ast_bounds: &[hir::GenericBound<'_>],
1034 let mut bounds = Bounds::default();
1036 self.add_bounds(param_ty, ast_bounds.iter(), &mut bounds, ty::List::empty());
1042 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1045 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1046 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1047 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1048 #[instrument(level = "debug", skip(self, bounds, speculative, dup_bindings, path_span))]
1049 fn add_predicates_for_ast_type_binding(
1051 hir_ref_id: hir::HirId,
1052 trait_ref: ty::PolyTraitRef<'tcx>,
1053 binding: &ConvertedBinding<'_, 'tcx>,
1054 bounds: &mut Bounds<'tcx>,
1056 dup_bindings: &mut FxHashMap<DefId, Span>,
1058 constness: ty::BoundConstness,
1059 ) -> Result<(), ErrorGuaranteed> {
1060 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1061 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1062 // subtle in the event that `T` is defined in a supertrait of
1063 // `SomeTrait`, because in that case we need to upcast.
1065 // That is, consider this case:
1068 // trait SubTrait: SuperTrait<i32> { }
1069 // trait SuperTrait<A> { type T; }
1071 // ... B: SubTrait<T = foo> ...
1074 // We want to produce `<B as SuperTrait<i32>>::T == foo`.
1076 let tcx = self.tcx();
1079 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1080 // Simple case: X is defined in the current trait.
1083 // Otherwise, we have to walk through the supertraits to find
1085 self.one_bound_for_assoc_type(
1086 || traits::supertraits(tcx, trait_ref),
1087 || trait_ref.print_only_trait_path().to_string(),
1090 || match binding.kind {
1091 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1097 let (assoc_ident, def_scope) =
1098 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1100 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1101 // of calling `filter_by_name_and_kind`.
1102 let find_item_of_kind = |kind| {
1103 tcx.associated_items(candidate.def_id())
1104 .filter_by_name_unhygienic(assoc_ident.name)
1105 .find(|i| i.kind == kind && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident)
1107 let assoc_item = find_item_of_kind(ty::AssocKind::Type)
1108 .or_else(|| find_item_of_kind(ty::AssocKind::Const))
1109 .expect("missing associated type");
1111 if !assoc_item.visibility(tcx).is_accessible_from(def_scope, tcx) {
1115 &format!("{} `{}` is private", assoc_item.kind, binding.item_name),
1117 .span_label(binding.span, &format!("private {}", assoc_item.kind))
1120 tcx.check_stability(assoc_item.def_id, Some(hir_ref_id), binding.span, None);
1124 .entry(assoc_item.def_id)
1125 .and_modify(|prev_span| {
1126 self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified {
1128 prev_span: *prev_span,
1129 item_name: binding.item_name,
1130 def_path: tcx.def_path_str(assoc_item.container_id(tcx)),
1133 .or_insert(binding.span);
1136 // Include substitutions for generic parameters of associated types
1137 let projection_ty = candidate.map_bound(|trait_ref| {
1138 let ident = Ident::new(assoc_item.name, binding.item_name.span);
1139 let item_segment = hir::PathSegment {
1141 hir_id: binding.hir_id,
1143 args: Some(binding.gen_args),
1147 let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item(
1154 debug!(?substs_trait_ref_and_assoc_item);
1156 self.tcx().mk_alias_ty(assoc_item.def_id, substs_trait_ref_and_assoc_item)
1160 // Find any late-bound regions declared in `ty` that are not
1161 // declared in the trait-ref or assoc_item. These are not well-formed.
1165 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1166 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1167 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1168 let late_bound_in_trait_ref =
1169 tcx.collect_constrained_late_bound_regions(&projection_ty);
1170 let late_bound_in_ty =
1171 tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty));
1172 debug!(?late_bound_in_trait_ref);
1173 debug!(?late_bound_in_ty);
1175 // FIXME: point at the type params that don't have appropriate lifetimes:
1176 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1177 // ---- ---- ^^^^^^^
1178 self.validate_late_bound_regions(
1179 late_bound_in_trait_ref,
1186 "binding for associated type `{}` references {}, \
1187 which does not appear in the trait input types",
1196 match binding.kind {
1197 ConvertedBindingKind::Equality(mut term) => {
1198 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1199 // the "projection predicate" for:
1201 // `<T as Iterator>::Item = u32`
1202 let assoc_item_def_id = projection_ty.skip_binder().def_id;
1203 let def_kind = tcx.def_kind(assoc_item_def_id);
1204 match (def_kind, term.unpack()) {
1205 (hir::def::DefKind::AssocTy, ty::TermKind::Ty(_))
1206 | (hir::def::DefKind::AssocConst, ty::TermKind::Const(_)) => (),
1208 let got = if let Some(_) = term.ty() { "type" } else { "constant" };
1209 let expected = def_kind.descr(assoc_item_def_id);
1210 let mut err = tcx.sess.struct_span_err(
1212 &format!("expected {expected} bound, found {got}"),
1215 tcx.def_span(assoc_item_def_id),
1216 &format!("{expected} defined here"),
1219 if let hir::def::DefKind::AssocConst = def_kind
1220 && let Some(t) = term.ty() && (t.is_enum() || t.references_error())
1221 && tcx.features().associated_const_equality {
1222 err.span_suggestion(
1224 "if equating a const, try wrapping with braces",
1225 format!("{} = {{ const }}", binding.item_name),
1226 Applicability::HasPlaceholders,
1229 let reported = err.emit();
1230 term = match def_kind {
1231 hir::def::DefKind::AssocTy => {
1232 tcx.ty_error_with_guaranteed(reported).into()
1234 hir::def::DefKind::AssocConst => tcx
1235 .const_error_with_guaranteed(
1236 tcx.bound_type_of(assoc_item_def_id)
1237 .subst(tcx, projection_ty.skip_binder().substs),
1241 _ => unreachable!(),
1245 bounds.push_projection_bound(
1248 .map_bound(|projection_ty| ty::ProjectionPredicate { projection_ty, term }),
1252 ConvertedBindingKind::Constraint(ast_bounds) => {
1253 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1255 // `<T as Iterator>::Item: Debug`
1257 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1258 // parameter to have a skipped binder.
1259 let param_ty = tcx.mk_ty(ty::Alias(ty::Projection, projection_ty.skip_binder()));
1260 self.add_bounds(param_ty, ast_bounds.iter(), bounds, candidate.bound_vars());
1270 item_segment: &hir::PathSegment<'_>,
1272 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1273 self.tcx().at(span).bound_type_of(did).subst(self.tcx(), substs)
1276 fn conv_object_ty_poly_trait_ref(
1279 hir_trait_bounds: &[hir::PolyTraitRef<'_>],
1280 lifetime: &hir::Lifetime,
1282 representation: DynKind,
1284 let tcx = self.tcx();
1286 let mut bounds = Bounds::default();
1287 let mut potential_assoc_types = Vec::new();
1288 let dummy_self = self.tcx().types.trait_object_dummy_self;
1289 for trait_bound in hir_trait_bounds.iter().rev() {
1290 if let GenericArgCountResult {
1292 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1294 } = self.instantiate_poly_trait_ref(
1295 &trait_bound.trait_ref,
1297 ty::BoundConstness::NotConst,
1302 potential_assoc_types.extend(cur_potential_assoc_types);
1306 let mut trait_bounds = vec![];
1307 let mut projection_bounds = vec![];
1308 for (pred, span) in bounds.predicates() {
1309 let bound_pred = pred.kind();
1310 match bound_pred.skip_binder() {
1311 ty::PredicateKind::Clause(clause) => match clause {
1312 ty::Clause::Trait(trait_pred) => {
1313 assert_eq!(trait_pred.polarity, ty::ImplPolarity::Positive);
1315 bound_pred.rebind(trait_pred.trait_ref),
1317 trait_pred.constness,
1320 ty::Clause::Projection(proj) => {
1321 projection_bounds.push((bound_pred.rebind(proj), span));
1323 ty::Clause::TypeOutlives(_) => {
1324 // Do nothing, we deal with regions separately
1326 ty::Clause::RegionOutlives(_) => bug!(),
1328 ty::PredicateKind::WellFormed(_)
1329 | ty::PredicateKind::ObjectSafe(_)
1330 | ty::PredicateKind::ClosureKind(_, _, _)
1331 | ty::PredicateKind::Subtype(_)
1332 | ty::PredicateKind::Coerce(_)
1333 | ty::PredicateKind::ConstEvaluatable(_)
1334 | ty::PredicateKind::ConstEquate(_, _)
1335 | ty::PredicateKind::TypeWellFormedFromEnv(_)
1336 | ty::PredicateKind::Ambiguous => bug!(),
1340 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1341 // is used and no 'maybe' bounds are used.
1342 let expanded_traits =
1343 traits::expand_trait_aliases(tcx, trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1345 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) = expanded_traits
1346 .filter(|i| i.trait_ref().self_ty().skip_binder() == dummy_self)
1347 .partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1348 if regular_traits.len() > 1 {
1349 let first_trait = ®ular_traits[0];
1350 let additional_trait = ®ular_traits[1];
1351 let mut err = struct_span_err!(
1353 additional_trait.bottom().1,
1355 "only auto traits can be used as additional traits in a trait object"
1357 additional_trait.label_with_exp_info(
1359 "additional non-auto trait",
1362 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1364 "consider creating a new trait with all of these as supertraits and using that \
1365 trait here instead: `trait NewTrait: {} {{}}`",
1368 .map(|t| t.trait_ref().print_only_trait_path().to_string())
1369 .collect::<Vec<_>>()
1373 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1374 for more information on them, visit \
1375 <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1380 if regular_traits.is_empty() && auto_traits.is_empty() {
1381 let trait_alias_span = trait_bounds
1383 .map(|&(trait_ref, _, _)| trait_ref.def_id())
1384 .find(|&trait_ref| tcx.is_trait_alias(trait_ref))
1385 .map(|trait_ref| tcx.def_span(trait_ref));
1387 tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span, trait_alias_span });
1388 return tcx.ty_error_with_guaranteed(reported);
1391 // Check that there are no gross object safety violations;
1392 // most importantly, that the supertraits don't contain `Self`,
1394 for item in ®ular_traits {
1395 let object_safety_violations =
1396 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1397 if !object_safety_violations.is_empty() {
1398 let reported = report_object_safety_error(
1401 item.trait_ref().def_id(),
1402 &object_safety_violations,
1405 return tcx.ty_error_with_guaranteed(reported);
1409 // Use a `BTreeSet` to keep output in a more consistent order.
1410 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1412 let regular_traits_refs_spans = trait_bounds
1414 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1416 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1417 assert_eq!(constness, ty::BoundConstness::NotConst);
1419 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1421 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1422 obligation.predicate
1425 let bound_predicate = obligation.predicate.kind();
1426 match bound_predicate.skip_binder() {
1427 ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => {
1428 let pred = bound_predicate.rebind(pred);
1429 associated_types.entry(span).or_default().extend(
1430 tcx.associated_items(pred.def_id())
1431 .in_definition_order()
1432 .filter(|item| item.kind == ty::AssocKind::Type)
1433 .map(|item| item.def_id),
1436 ty::PredicateKind::Clause(ty::Clause::Projection(pred)) => {
1437 let pred = bound_predicate.rebind(pred);
1438 // A `Self` within the original bound will be substituted with a
1439 // `trait_object_dummy_self`, so check for that.
1440 let references_self = match pred.skip_binder().term.unpack() {
1441 ty::TermKind::Ty(ty) => ty.walk().any(|arg| arg == dummy_self.into()),
1442 ty::TermKind::Const(c) => {
1443 c.ty().walk().any(|arg| arg == dummy_self.into())
1447 // If the projection output contains `Self`, force the user to
1448 // elaborate it explicitly to avoid a lot of complexity.
1450 // The "classically useful" case is the following:
1452 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1457 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1458 // but actually supporting that would "expand" to an infinitely-long type
1459 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1461 // Instead, we force the user to write
1462 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1463 // the discussion in #56288 for alternatives.
1464 if !references_self {
1465 // Include projections defined on supertraits.
1466 projection_bounds.push((pred, span));
1474 for (projection_bound, _) in &projection_bounds {
1475 for def_ids in associated_types.values_mut() {
1476 def_ids.remove(&projection_bound.projection_def_id());
1480 self.complain_about_missing_associated_types(
1482 potential_assoc_types,
1486 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1487 // `dyn Trait + Send`.
1488 // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering
1490 let mut duplicates = FxHashSet::default();
1491 auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id()));
1492 debug!("regular_traits: {:?}", regular_traits);
1493 debug!("auto_traits: {:?}", auto_traits);
1495 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1496 let existential_trait_refs = regular_traits.iter().map(|i| {
1497 i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| {
1498 assert_eq!(trait_ref.self_ty(), dummy_self);
1500 // Verify that `dummy_self` did not leak inside default type parameters. This
1501 // could not be done at path creation, since we need to see through trait aliases.
1502 let mut missing_type_params = vec![];
1503 let mut references_self = false;
1504 let generics = tcx.generics_of(trait_ref.def_id);
1505 let substs: Vec<_> = trait_ref
1509 .skip(1) // Remove `Self` for `ExistentialPredicate`.
1510 .map(|(index, arg)| {
1511 if arg == dummy_self.into() {
1512 let param = &generics.params[index];
1513 missing_type_params.push(param.name);
1514 return tcx.ty_error().into();
1515 } else if arg.walk().any(|arg| arg == dummy_self.into()) {
1516 references_self = true;
1517 return tcx.ty_error().into();
1522 let substs = tcx.intern_substs(&substs[..]);
1524 let span = i.bottom().1;
1525 let empty_generic_args = hir_trait_bounds.iter().any(|hir_bound| {
1526 hir_bound.trait_ref.path.res == Res::Def(DefKind::Trait, trait_ref.def_id)
1527 && hir_bound.span.contains(span)
1529 self.complain_about_missing_type_params(
1530 missing_type_params,
1536 if references_self {
1537 let def_id = i.bottom().0.def_id();
1538 let mut err = struct_span_err!(
1542 "the {} `{}` cannot be made into an object",
1543 tcx.def_kind(def_id).descr(def_id),
1544 tcx.item_name(def_id),
1547 rustc_middle::traits::ObjectSafetyViolation::SupertraitSelf(smallvec![])
1553 ty::ExistentialTraitRef { def_id: trait_ref.def_id, substs }
1557 let existential_projections = projection_bounds.iter().map(|(bound, _)| {
1558 bound.map_bound(|mut b| {
1559 assert_eq!(b.projection_ty.self_ty(), dummy_self);
1561 // Like for trait refs, verify that `dummy_self` did not leak inside default type
1563 let references_self = b.projection_ty.substs.iter().skip(1).any(|arg| {
1564 if arg.walk().any(|arg| arg == dummy_self.into()) {
1569 if references_self {
1571 .delay_span_bug(span, "trait object projection bounds reference `Self`");
1572 let substs: Vec<_> = b
1577 if arg.walk().any(|arg| arg == dummy_self.into()) {
1578 return tcx.ty_error().into();
1583 b.projection_ty.substs = tcx.intern_substs(&substs[..]);
1586 ty::ExistentialProjection::erase_self_ty(tcx, b)
1590 let regular_trait_predicates = existential_trait_refs
1591 .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait));
1592 let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| {
1593 ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()))
1595 // N.b. principal, projections, auto traits
1596 // FIXME: This is actually wrong with multiple principals in regards to symbol mangling
1597 let mut v = regular_trait_predicates
1599 existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)),
1601 .chain(auto_trait_predicates)
1602 .collect::<SmallVec<[_; 8]>>();
1603 v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
1605 let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter());
1607 // Use explicitly-specified region bound.
1608 let region_bound = if !lifetime.is_elided() {
1609 self.ast_region_to_region(lifetime, None)
1611 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1612 if tcx.named_region(lifetime.hir_id).is_some() {
1613 self.ast_region_to_region(lifetime, None)
1615 self.re_infer(None, span).unwrap_or_else(|| {
1616 let mut err = struct_span_err!(
1620 "the lifetime bound for this object type cannot be deduced \
1621 from context; please supply an explicit bound"
1624 // We will have already emitted an error E0106 complaining about a
1625 // missing named lifetime in `&dyn Trait`, so we elide this one.
1630 tcx.lifetimes.re_static
1635 debug!("region_bound: {:?}", region_bound);
1637 let ty = tcx.mk_dynamic(existential_predicates, region_bound, representation);
1638 debug!("trait_object_type: {:?}", ty);
1642 fn report_ambiguous_associated_type(
1648 ) -> ErrorGuaranteed {
1649 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1653 .confused_type_with_std_module
1655 .any(|full_span| full_span.contains(span))
1657 err.span_suggestion_verbose(
1658 span.shrink_to_lo(),
1659 "you are looking for the module in `std`, not the primitive type",
1661 Applicability::MachineApplicable,
1664 match (types, traits) {
1666 err.span_suggestion_verbose(
1669 "if there were a type named `Type` that implements a trait named \
1670 `Trait` with associated type `{name}`, you could use the \
1671 fully-qualified path",
1673 format!("<Type as Trait>::{name}"),
1674 Applicability::HasPlaceholders,
1677 ([], [trait_str]) => {
1678 err.span_suggestion_verbose(
1681 "if there were a type named `Example` that implemented `{trait_str}`, \
1682 you could use the fully-qualified path",
1684 format!("<Example as {trait_str}>::{name}"),
1685 Applicability::HasPlaceholders,
1689 err.span_suggestions(
1692 "if there were a type named `Example` that implemented one of the \
1693 traits with associated type `{name}`, you could use the \
1694 fully-qualified path",
1698 .map(|trait_str| format!("<Example as {trait_str}>::{name}"))
1699 .collect::<Vec<_>>(),
1700 Applicability::HasPlaceholders,
1703 ([type_str], []) => {
1704 err.span_suggestion_verbose(
1707 "if there were a trait named `Example` with associated type `{name}` \
1708 implemented for `{type_str}`, you could use the fully-qualified path",
1710 format!("<{type_str} as Example>::{name}"),
1711 Applicability::HasPlaceholders,
1715 err.span_suggestions(
1718 "if there were a trait named `Example` with associated type `{name}` \
1719 implemented for one of the types, you could use the fully-qualified \
1724 .map(|type_str| format!("<{type_str} as Example>::{name}")),
1725 Applicability::HasPlaceholders,
1728 (types, traits) => {
1729 let mut suggestions = vec![];
1730 for type_str in types {
1731 for trait_str in traits {
1732 suggestions.push(format!("<{type_str} as {trait_str}>::{name}"));
1735 err.span_suggestions(
1737 "use the fully-qualified path",
1739 Applicability::MachineApplicable,
1747 // Search for a bound on a type parameter which includes the associated item
1748 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1749 // This function will fail if there are no suitable bounds or there is
1751 fn find_bound_for_assoc_item(
1753 ty_param_def_id: LocalDefId,
1756 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1757 let tcx = self.tcx();
1760 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1761 ty_param_def_id, assoc_name, span,
1764 let predicates = &self
1765 .get_type_parameter_bounds(span, ty_param_def_id.to_def_id(), assoc_name)
1768 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1770 let param_name = tcx.hir().ty_param_name(ty_param_def_id);
1771 self.one_bound_for_assoc_type(
1773 traits::transitive_bounds_that_define_assoc_type(
1775 predicates.iter().filter_map(|(p, _)| {
1776 Some(p.to_opt_poly_trait_pred()?.map_bound(|t| t.trait_ref))
1781 || param_name.to_string(),
1788 // Checks that `bounds` contains exactly one element and reports appropriate
1789 // errors otherwise.
1790 #[instrument(level = "debug", skip(self, all_candidates, ty_param_name, is_equality), ret)]
1791 fn one_bound_for_assoc_type<I>(
1793 all_candidates: impl Fn() -> I,
1794 ty_param_name: impl Fn() -> String,
1797 is_equality: impl Fn() -> Option<String>,
1798 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1800 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1802 let mut matching_candidates = all_candidates()
1803 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1804 let mut const_candidates = all_candidates()
1805 .filter(|r| self.trait_defines_associated_const_named(r.def_id(), assoc_name));
1807 let (bound, next_cand) = match (matching_candidates.next(), const_candidates.next()) {
1808 (Some(bound), _) => (bound, matching_candidates.next()),
1809 (None, Some(bound)) => (bound, const_candidates.next()),
1811 let reported = self.complain_about_assoc_type_not_found(
1817 return Err(reported);
1822 if let Some(bound2) = next_cand {
1825 let is_equality = is_equality();
1826 let bounds = IntoIterator::into_iter([bound, bound2]).chain(matching_candidates);
1827 let mut err = if is_equality.is_some() {
1828 // More specific Error Index entry.
1833 "ambiguous associated type `{}` in bounds of `{}`",
1842 "ambiguous associated type `{}` in bounds of `{}`",
1847 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1849 let mut where_bounds = vec![];
1850 for bound in bounds {
1851 let bound_id = bound.def_id();
1852 let bound_span = self
1854 .associated_items(bound_id)
1855 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
1856 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1858 if let Some(bound_span) = bound_span {
1862 "ambiguous `{}` from `{}`",
1864 bound.print_only_trait_path(),
1867 if let Some(constraint) = &is_equality {
1868 where_bounds.push(format!(
1869 " T: {trait}::{assoc} = {constraint}",
1870 trait=bound.print_only_trait_path(),
1872 constraint=constraint,
1875 err.span_suggestion_verbose(
1876 span.with_hi(assoc_name.span.lo()),
1877 "use fully qualified syntax to disambiguate",
1881 bound.print_only_trait_path(),
1883 Applicability::MaybeIncorrect,
1888 "associated type `{}` could derive from `{}`",
1890 bound.print_only_trait_path(),
1894 if !where_bounds.is_empty() {
1896 "consider introducing a new type parameter `T` and adding `where` constraints:\
1897 \n where\n T: {},\n{}",
1899 where_bounds.join(",\n"),
1902 let reported = err.emit();
1903 if !where_bounds.is_empty() {
1904 return Err(reported);
1911 // Create a type from a path to an associated type or to an enum variant.
1912 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1913 // and item_segment is the path segment for `D`. We return a type and a def for
1915 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1916 // parameter or `Self`.
1917 // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1918 // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
1919 #[instrument(level = "debug", skip(self, hir_ref_id, span, qself, assoc_segment), fields(assoc_ident=?assoc_segment.ident), ret)]
1920 pub fn associated_path_to_ty(
1922 hir_ref_id: hir::HirId,
1925 qself: &hir::Ty<'_>,
1926 assoc_segment: &hir::PathSegment<'_>,
1927 permit_variants: bool,
1928 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1929 let tcx = self.tcx();
1930 let assoc_ident = assoc_segment.ident;
1931 let qself_res = if let hir::TyKind::Path(hir::QPath::Resolved(_, path)) = &qself.kind {
1937 // Check if we have an enum variant.
1938 let mut variant_resolution = None;
1939 if let Some(adt_def) = self.probe_adt(span, qself_ty) {
1940 if adt_def.is_enum() {
1941 let variant_def = adt_def
1944 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident(tcx), adt_def.did()));
1945 if let Some(variant_def) = variant_def {
1946 if permit_variants {
1947 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None);
1948 self.prohibit_generics(slice::from_ref(assoc_segment).iter(), |err| {
1949 err.note("enum variants can't have type parameters");
1950 let type_name = tcx.item_name(adt_def.did());
1952 "you might have meant to specity type parameters on enum \
1955 let Some(args) = assoc_segment.args else { return; };
1956 // Get the span of the generics args *including* the leading `::`.
1957 let args_span = assoc_segment.ident.span.shrink_to_hi().to(args.span_ext);
1958 if tcx.generics_of(adt_def.did()).count() == 0 {
1959 // FIXME(estebank): we could also verify that the arguments being
1960 // work for the `enum`, instead of just looking if it takes *any*.
1961 err.span_suggestion_verbose(
1963 &format!("{type_name} doesn't have generic parameters"),
1965 Applicability::MachineApplicable,
1969 let Ok(snippet) = tcx.sess.source_map().span_to_snippet(args_span) else {
1973 let (qself_sugg_span, is_self) = if let hir::TyKind::Path(
1974 hir::QPath::Resolved(_, path)
1976 // If the path segment already has type params, we want to overwrite
1978 match &path.segments[..] {
1979 // `segment` is the previous to last element on the path,
1980 // which would normally be the `enum` itself, while the last
1981 // `_` `PathSegment` corresponds to the variant.
1982 [.., hir::PathSegment {
1985 res: Res::Def(DefKind::Enum, _),
1988 // We need to include the `::` in `Type::Variant::<Args>`
1989 // to point the span to `::<Args>`, not just `<Args>`.
1990 ident.span.shrink_to_hi().to(args.map_or(
1991 ident.span.shrink_to_hi(),
1996 // We need to include the `::` in `Type::Variant::<Args>`
1997 // to point the span to `::<Args>`, not just `<Args>`.
1998 segment.ident.span.shrink_to_hi().to(segment.args.map_or(
1999 segment.ident.span.shrink_to_hi(),
2001 kw::SelfUpper == segment.ident.name,
2012 let suggestion = vec![
2014 // Account for people writing `Self::Variant::<Args>`, where
2015 // `Self` is the enum, and suggest replacing `Self` with the
2016 // appropriate type: `Type::<Args>::Variant`.
2017 (qself.span, format!("{type_name}{snippet}"))
2019 (qself_sugg_span, snippet)
2021 (args_span, String::new()),
2023 err.multipart_suggestion_verbose(
2026 Applicability::MaybeIncorrect,
2029 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
2031 variant_resolution = Some(variant_def.def_id);
2036 // see if we can satisfy using an inherent associated type
2037 for &impl_ in tcx.inherent_impls(adt_def.did()) {
2038 let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, impl_) else {
2041 let ty::Adt(_, adt_substs) = qself_ty.kind() else {
2042 // FIXME(inherent_associated_types)
2043 bug!("unimplemented: non-adt self of inherent assoc ty");
2045 let item_substs = self.create_substs_for_associated_item(
2051 let ty = tcx.bound_type_of(assoc_ty_did).subst(tcx, item_substs);
2052 return Ok((ty, DefKind::AssocTy, assoc_ty_did));
2056 // Find the type of the associated item, and the trait where the associated
2057 // item is declared.
2058 let bound = match (&qself_ty.kind(), qself_res) {
2059 (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
2060 // `Self` in an impl of a trait -- we have a concrete self type and a
2062 let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) else {
2063 // A cycle error occurred, most likely.
2064 let guar = tcx.sess.delay_span_bug(span, "expected cycle error");
2068 self.one_bound_for_assoc_type(
2069 || traits::supertraits(tcx, ty::Binder::dummy(trait_ref.subst_identity())),
2070 || "Self".to_string(),
2078 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
2079 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
2081 let reported = if variant_resolution.is_some() {
2082 // Variant in type position
2083 let msg = format!("expected type, found variant `{}`", assoc_ident);
2084 tcx.sess.span_err(span, &msg)
2085 } else if qself_ty.is_enum() {
2086 let mut err = struct_span_err!(
2090 "no variant named `{}` found for enum `{}`",
2095 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2096 if let Some(suggested_name) = find_best_match_for_name(
2100 .map(|variant| variant.name)
2101 .collect::<Vec<Symbol>>(),
2105 err.span_suggestion(
2107 "there is a variant with a similar name",
2109 Applicability::MaybeIncorrect,
2114 format!("variant not found in `{}`", qself_ty),
2118 if let Some(sp) = tcx.hir().span_if_local(adt_def.did()) {
2119 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2123 } else if let Err(reported) = qself_ty.error_reported() {
2125 } else if let ty::Alias(ty::Opaque, alias_ty) = qself_ty.kind() {
2126 // `<impl Trait as OtherTrait>::Assoc` makes no sense.
2129 tcx.def_span(alias_ty.def_id),
2131 "`impl Trait` is not allowed in path parameters"
2133 .emit() // Already reported in an earlier stage.
2135 // Find all the `impl`s that `qself_ty` has for any trait that has the
2136 // associated type, so that we suggest the right one.
2137 let infcx = tcx.infer_ctxt().build();
2138 // We create a fresh `ty::ParamEnv` instead of the one for `self.item_def_id()`
2139 // to avoid a cycle error in `src/test/ui/resolve/issue-102946.rs`.
2140 let param_env = ty::ParamEnv::empty();
2141 let traits: Vec<_> = self
2144 .filter(|trait_def_id| {
2145 // Consider only traits with the associated type
2146 tcx.associated_items(*trait_def_id)
2147 .in_definition_order()
2149 i.kind.namespace() == Namespace::TypeNS
2150 && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident
2151 && matches!(i.kind, ty::AssocKind::Type)
2153 // Consider only accessible traits
2154 && tcx.visibility(*trait_def_id)
2155 .is_accessible_from(self.item_def_id(), tcx)
2156 && tcx.all_impls(*trait_def_id)
2157 .any(|impl_def_id| {
2158 let trait_ref = tcx.impl_trait_ref(impl_def_id);
2159 trait_ref.map_or(false, |trait_ref| {
2160 let impl_ = trait_ref.subst(
2162 infcx.fresh_substs_for_item(span, impl_def_id),
2167 tcx.erase_regions(impl_.self_ty()),
2168 tcx.erase_regions(qself_ty),
2172 && tcx.impl_polarity(impl_def_id) != ty::ImplPolarity::Negative
2175 .map(|trait_def_id| tcx.def_path_str(trait_def_id))
2178 // Don't print `TyErr` to the user.
2179 self.report_ambiguous_associated_type(
2181 &[qself_ty.to_string()],
2186 return Err(reported);
2190 let trait_did = bound.def_id();
2191 let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, trait_did) else {
2192 // Assume that if it's not matched, there must be a const defined with the same name
2193 // but it was used in a type position.
2194 let msg = format!("found associated const `{assoc_ident}` when type was expected");
2195 let guar = tcx.sess.struct_span_err(span, &msg).emit();
2199 let ty = self.projected_ty_from_poly_trait_ref(span, assoc_ty_did, assoc_segment, bound);
2201 if let Some(variant_def_id) = variant_resolution {
2202 tcx.struct_span_lint_hir(
2203 AMBIGUOUS_ASSOCIATED_ITEMS,
2206 "ambiguous associated item",
2208 let mut could_refer_to = |kind: DefKind, def_id, also| {
2209 let note_msg = format!(
2210 "`{}` could{} refer to the {} defined here",
2215 lint.span_note(tcx.def_span(def_id), ¬e_msg);
2218 could_refer_to(DefKind::Variant, variant_def_id, "");
2219 could_refer_to(DefKind::AssocTy, assoc_ty_did, " also");
2221 lint.span_suggestion(
2223 "use fully-qualified syntax",
2224 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2225 Applicability::MachineApplicable,
2232 Ok((ty, DefKind::AssocTy, assoc_ty_did))
2241 ) -> Option<DefId> {
2242 let tcx = self.tcx();
2243 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
2245 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
2246 // of calling `find_by_name_and_kind`.
2247 let item = tcx.associated_items(scope).in_definition_order().find(|i| {
2248 i.kind.namespace() == Namespace::TypeNS
2249 && i.ident(tcx).normalize_to_macros_2_0() == ident
2252 let kind = DefKind::AssocTy;
2253 if !item.visibility(tcx).is_accessible_from(def_scope, tcx) {
2254 let kind = kind.descr(item.def_id);
2255 let msg = format!("{kind} `{ident}` is private");
2256 let def_span = self.tcx().def_span(item.def_id);
2258 .struct_span_err_with_code(span, &msg, rustc_errors::error_code!(E0624))
2259 .span_label(span, &format!("private {kind}"))
2260 .span_label(def_span, &format!("{kind} defined here"))
2263 tcx.check_stability(item.def_id, Some(block), span, None);
2271 opt_self_ty: Option<Ty<'tcx>>,
2273 trait_segment: &hir::PathSegment<'_>,
2274 item_segment: &hir::PathSegment<'_>,
2275 constness: ty::BoundConstness,
2277 let tcx = self.tcx();
2279 let trait_def_id = tcx.parent(item_def_id);
2281 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2283 let Some(self_ty) = opt_self_ty else {
2284 let path_str = tcx.def_path_str(trait_def_id);
2286 let def_id = self.item_def_id();
2288 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2290 let parent_def_id = def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
2291 .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id());
2293 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2295 // If the trait in segment is the same as the trait defining the item,
2296 // use the `<Self as ..>` syntax in the error.
2297 let is_part_of_self_trait_constraints = def_id == trait_def_id;
2298 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2300 let type_names = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2301 vec!["Self".to_string()]
2303 // Find all the types that have an `impl` for the trait.
2304 tcx.all_impls(trait_def_id)
2305 .filter(|impl_def_id| {
2306 // Consider only accessible traits
2307 tcx.visibility(*impl_def_id).is_accessible_from(self.item_def_id(), tcx)
2308 && tcx.impl_polarity(impl_def_id) != ty::ImplPolarity::Negative
2310 .filter_map(|impl_def_id| tcx.impl_trait_ref(impl_def_id))
2311 .map(|impl_| impl_.subst_identity().self_ty())
2312 // We don't care about blanket impls.
2313 .filter(|self_ty| !self_ty.has_non_region_param())
2314 .map(|self_ty| tcx.erase_regions(self_ty).to_string())
2317 // FIXME: also look at `tcx.generics_of(self.item_def_id()).params` any that
2318 // references the trait. Relevant for the first case in
2319 // `src/test/ui/associated-types/associated-types-in-ambiguous-context.rs`
2320 let reported = self.report_ambiguous_associated_type(
2324 item_segment.ident.name,
2326 return tcx.ty_error_with_guaranteed(reported)
2329 debug!("qpath_to_ty: self_type={:?}", self_ty);
2331 let trait_ref = self.ast_path_to_mono_trait_ref(
2340 let item_substs = self.create_substs_for_associated_item(
2347 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2349 tcx.mk_projection(item_def_id, item_substs)
2352 pub fn prohibit_generics<'a>(
2354 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
2355 extend: impl Fn(&mut Diagnostic),
2357 let args = segments.clone().flat_map(|segment| segment.args().args);
2359 let (lt, ty, ct, inf) =
2360 args.clone().fold((false, false, false, false), |(lt, ty, ct, inf), arg| match arg {
2361 hir::GenericArg::Lifetime(_) => (true, ty, ct, inf),
2362 hir::GenericArg::Type(_) => (lt, true, ct, inf),
2363 hir::GenericArg::Const(_) => (lt, ty, true, inf),
2364 hir::GenericArg::Infer(_) => (lt, ty, ct, true),
2366 let mut emitted = false;
2367 if lt || ty || ct || inf {
2368 let types_and_spans: Vec<_> = segments
2370 .flat_map(|segment| {
2371 if segment.args().args.is_empty() {
2376 Res::PrimTy(ty) => format!("{} `{}`", segment.res.descr(), ty.name()),
2378 if let Some(name) = self.tcx().opt_item_name(def_id) => {
2379 format!("{} `{name}`", segment.res.descr())
2381 Res::Err => "this type".to_string(),
2382 _ => segment.res.descr().to_string(),
2389 let this_type = match &types_and_spans[..] {
2390 [.., _, (last, _)] => format!(
2392 types_and_spans[..types_and_spans.len() - 1]
2394 .map(|(x, _)| x.as_str())
2396 .collect::<String>()
2398 [(only, _)] => only.to_string(),
2399 [] => "this type".to_string(),
2402 let arg_spans: Vec<Span> = args.map(|arg| arg.span()).collect();
2404 let mut kinds = Vec::with_capacity(4);
2406 kinds.push("lifetime");
2412 kinds.push("const");
2415 kinds.push("generic");
2417 let (kind, s) = match kinds[..] {
2421 kinds[..kinds.len() - 1]
2425 .collect::<String>()
2429 [only] => (only.to_string(), ""),
2430 [] => unreachable!(),
2432 let last_span = *arg_spans.last().unwrap();
2433 let span: MultiSpan = arg_spans.into();
2434 let mut err = struct_span_err!(
2438 "{kind} arguments are not allowed on {this_type}",
2440 err.span_label(last_span, format!("{kind} argument{s} not allowed"));
2441 for (what, span) in types_and_spans {
2442 err.span_label(span, format!("not allowed on {what}"));
2449 for segment in segments {
2450 // Only emit the first error to avoid overloading the user with error messages.
2451 if let Some(b) = segment.args().bindings.first() {
2452 prohibit_assoc_ty_binding(self.tcx(), b.span);
2459 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2460 pub fn def_ids_for_value_path_segments(
2462 segments: &[hir::PathSegment<'_>],
2463 self_ty: Option<Ty<'tcx>>,
2468 // We need to extract the type parameters supplied by the user in
2469 // the path `path`. Due to the current setup, this is a bit of a
2470 // tricky-process; the problem is that resolve only tells us the
2471 // end-point of the path resolution, and not the intermediate steps.
2472 // Luckily, we can (at least for now) deduce the intermediate steps
2473 // just from the end-point.
2475 // There are basically five cases to consider:
2477 // 1. Reference to a constructor of a struct:
2479 // struct Foo<T>(...)
2481 // In this case, the parameters are declared in the type space.
2483 // 2. Reference to a constructor of an enum variant:
2485 // enum E<T> { Foo(...) }
2487 // In this case, the parameters are defined in the type space,
2488 // but may be specified either on the type or the variant.
2490 // 3. Reference to a fn item or a free constant:
2494 // In this case, the path will again always have the form
2495 // `a::b::foo::<T>` where only the final segment should have
2496 // type parameters. However, in this case, those parameters are
2497 // declared on a value, and hence are in the `FnSpace`.
2499 // 4. Reference to a method or an associated constant:
2501 // impl<A> SomeStruct<A> {
2505 // Here we can have a path like
2506 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2507 // may appear in two places. The penultimate segment,
2508 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2509 // final segment, `foo::<B>` contains parameters in fn space.
2511 // The first step then is to categorize the segments appropriately.
2513 let tcx = self.tcx();
2515 assert!(!segments.is_empty());
2516 let last = segments.len() - 1;
2518 let mut path_segs = vec![];
2521 // Case 1. Reference to a struct constructor.
2522 DefKind::Ctor(CtorOf::Struct, ..) => {
2523 // Everything but the final segment should have no
2524 // parameters at all.
2525 let generics = tcx.generics_of(def_id);
2526 // Variant and struct constructors use the
2527 // generics of their parent type definition.
2528 let generics_def_id = generics.parent.unwrap_or(def_id);
2529 path_segs.push(PathSeg(generics_def_id, last));
2532 // Case 2. Reference to a variant constructor.
2533 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2534 let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2535 let adt_def = self.probe_adt(span, self_ty).unwrap();
2536 debug_assert!(adt_def.is_enum());
2537 (adt_def.did(), last)
2538 } else if last >= 1 && segments[last - 1].args.is_some() {
2539 // Everything but the penultimate segment should have no
2540 // parameters at all.
2541 let mut def_id = def_id;
2543 // `DefKind::Ctor` -> `DefKind::Variant`
2544 if let DefKind::Ctor(..) = kind {
2545 def_id = tcx.parent(def_id);
2548 // `DefKind::Variant` -> `DefKind::Enum`
2549 let enum_def_id = tcx.parent(def_id);
2550 (enum_def_id, last - 1)
2552 // FIXME: lint here recommending `Enum::<...>::Variant` form
2553 // instead of `Enum::Variant::<...>` form.
2555 // Everything but the final segment should have no
2556 // parameters at all.
2557 let generics = tcx.generics_of(def_id);
2558 // Variant and struct constructors use the
2559 // generics of their parent type definition.
2560 (generics.parent.unwrap_or(def_id), last)
2562 path_segs.push(PathSeg(generics_def_id, index));
2565 // Case 3. Reference to a top-level value.
2566 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static(_) => {
2567 path_segs.push(PathSeg(def_id, last));
2570 // Case 4. Reference to a method or associated const.
2571 DefKind::AssocFn | DefKind::AssocConst => {
2572 if segments.len() >= 2 {
2573 let generics = tcx.generics_of(def_id);
2574 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2576 path_segs.push(PathSeg(def_id, last));
2579 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2582 debug!("path_segs = {:?}", path_segs);
2587 /// Check a type `Path` and convert it to a `Ty`.
2590 opt_self_ty: Option<Ty<'tcx>>,
2591 path: &hir::Path<'_>,
2592 permit_variants: bool,
2594 let tcx = self.tcx();
2597 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2598 path.res, opt_self_ty, path.segments
2601 let span = path.span;
2603 Res::Def(DefKind::OpaqueTy | DefKind::ImplTraitPlaceholder, did) => {
2604 // Check for desugared `impl Trait`.
2605 assert!(tcx.is_type_alias_impl_trait(did));
2606 let item_segment = path.segments.split_last().unwrap();
2607 self.prohibit_generics(item_segment.1.iter(), |err| {
2608 err.note("`impl Trait` types can't have type parameters");
2610 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2611 tcx.mk_opaque(did, substs)
2618 | DefKind::ForeignTy,
2621 assert_eq!(opt_self_ty, None);
2622 self.prohibit_generics(path.segments.split_last().unwrap().1.iter(), |_| {});
2623 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2625 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2626 // Convert "variant type" as if it were a real type.
2627 // The resulting `Ty` is type of the variant's enum for now.
2628 assert_eq!(opt_self_ty, None);
2631 self.def_ids_for_value_path_segments(path.segments, None, kind, def_id, span);
2632 let generic_segs: FxHashSet<_> =
2633 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2634 self.prohibit_generics(
2635 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2636 if !generic_segs.contains(&index) { Some(seg) } else { None }
2639 err.note("enum variants can't have type parameters");
2643 let PathSeg(def_id, index) = path_segs.last().unwrap();
2644 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2646 Res::Def(DefKind::TyParam, def_id) => {
2647 assert_eq!(opt_self_ty, None);
2648 self.prohibit_generics(path.segments.iter(), |err| {
2649 if let Some(span) = tcx.def_ident_span(def_id) {
2650 let name = tcx.item_name(def_id);
2651 err.span_note(span, &format!("type parameter `{name}` defined here"));
2655 let def_id = def_id.expect_local();
2656 let item_def_id = tcx.hir().ty_param_owner(def_id);
2657 let generics = tcx.generics_of(item_def_id);
2658 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2659 tcx.mk_ty_param(index, tcx.hir().ty_param_name(def_id))
2661 Res::SelfTyParam { .. } => {
2662 // `Self` in trait or type alias.
2663 assert_eq!(opt_self_ty, None);
2664 self.prohibit_generics(path.segments.iter(), |err| {
2665 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments[..] {
2666 err.span_suggestion_verbose(
2667 ident.span.shrink_to_hi().to(args.span_ext),
2668 "the `Self` type doesn't accept type parameters",
2670 Applicability::MaybeIncorrect,
2674 tcx.types.self_param
2676 Res::SelfTyAlias { alias_to: def_id, forbid_generic, .. } => {
2677 // `Self` in impl (we know the concrete type).
2678 assert_eq!(opt_self_ty, None);
2679 // Try to evaluate any array length constants.
2680 let ty = tcx.at(span).type_of(def_id);
2681 let span_of_impl = tcx.span_of_impl(def_id);
2682 self.prohibit_generics(path.segments.iter(), |err| {
2683 let def_id = match *ty.kind() {
2684 ty::Adt(self_def, _) => self_def.did(),
2688 let type_name = tcx.item_name(def_id);
2689 let span_of_ty = tcx.def_ident_span(def_id);
2690 let generics = tcx.generics_of(def_id).count();
2692 let msg = format!("`Self` is of type `{ty}`");
2693 if let (Ok(i_sp), Some(t_sp)) = (span_of_impl, span_of_ty) {
2694 let mut span: MultiSpan = vec![t_sp].into();
2695 span.push_span_label(
2697 &format!("`Self` is on type `{type_name}` in this `impl`"),
2699 let mut postfix = "";
2701 postfix = ", which doesn't have generic parameters";
2703 span.push_span_label(
2705 &format!("`Self` corresponds to this type{postfix}"),
2707 err.span_note(span, &msg);
2711 for segment in path.segments {
2712 if let Some(args) = segment.args && segment.ident.name == kw::SelfUpper {
2714 // FIXME(estebank): we could also verify that the arguments being
2715 // work for the `enum`, instead of just looking if it takes *any*.
2716 err.span_suggestion_verbose(
2717 segment.ident.span.shrink_to_hi().to(args.span_ext),
2718 "the `Self` type doesn't accept type parameters",
2720 Applicability::MachineApplicable,
2724 err.span_suggestion_verbose(
2727 "the `Self` type doesn't accept type parameters, use the \
2728 concrete type's name `{type_name}` instead if you want to \
2729 specify its type parameters"
2732 Applicability::MaybeIncorrect,
2738 // HACK(min_const_generics): Forbid generic `Self` types
2739 // here as we can't easily do that during nameres.
2741 // We do this before normalization as we otherwise allow
2743 // trait AlwaysApplicable { type Assoc; }
2744 // impl<T: ?Sized> AlwaysApplicable for T { type Assoc = usize; }
2746 // trait BindsParam<T> {
2749 // impl<T> BindsParam<T> for <T as AlwaysApplicable>::Assoc {
2750 // type ArrayTy = [u8; Self::MAX];
2753 // Note that the normalization happens in the param env of
2754 // the anon const, which is empty. This is why the
2755 // `AlwaysApplicable` impl needs a `T: ?Sized` bound for
2756 // this to compile if we were to normalize here.
2757 if forbid_generic && ty.needs_subst() {
2758 let mut err = tcx.sess.struct_span_err(
2760 "generic `Self` types are currently not permitted in anonymous constants",
2762 if let Some(hir::Node::Item(&hir::Item {
2763 kind: hir::ItemKind::Impl(impl_),
2765 })) = tcx.hir().get_if_local(def_id)
2767 err.span_note(impl_.self_ty.span, "not a concrete type");
2769 tcx.ty_error_with_guaranteed(err.emit())
2774 Res::Def(DefKind::AssocTy, def_id) => {
2775 debug_assert!(path.segments.len() >= 2);
2776 self.prohibit_generics(path.segments[..path.segments.len() - 2].iter(), |_| {});
2777 // HACK: until we support `<Type as ~const Trait>`, assume all of them are.
2778 let constness = if tcx.has_attr(tcx.parent(def_id), sym::const_trait) {
2779 ty::BoundConstness::ConstIfConst
2781 ty::BoundConstness::NotConst
2787 &path.segments[path.segments.len() - 2],
2788 path.segments.last().unwrap(),
2792 Res::PrimTy(prim_ty) => {
2793 assert_eq!(opt_self_ty, None);
2794 self.prohibit_generics(path.segments.iter(), |err| {
2795 let name = prim_ty.name_str();
2796 for segment in path.segments {
2797 if let Some(args) = segment.args {
2798 err.span_suggestion_verbose(
2799 segment.ident.span.shrink_to_hi().to(args.span_ext),
2800 &format!("primitive type `{name}` doesn't have generic parameters"),
2802 Applicability::MaybeIncorrect,
2808 hir::PrimTy::Bool => tcx.types.bool,
2809 hir::PrimTy::Char => tcx.types.char,
2810 hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2811 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2812 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2813 hir::PrimTy::Str => tcx.types.str_,
2820 .delay_span_bug(path.span, "path with `Res::Err` but no error emitted");
2821 self.set_tainted_by_errors(e);
2822 self.tcx().ty_error_with_guaranteed(e)
2824 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2828 /// Parses the programmer's textual representation of a type into our
2829 /// internal notion of a type.
2830 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2831 self.ast_ty_to_ty_inner(ast_ty, false, false)
2834 /// Parses the programmer's textual representation of a type into our
2835 /// internal notion of a type. This is meant to be used within a path.
2836 pub fn ast_ty_to_ty_in_path(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2837 self.ast_ty_to_ty_inner(ast_ty, false, true)
2840 /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2841 /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2842 #[instrument(level = "debug", skip(self), ret)]
2843 fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool, in_path: bool) -> Ty<'tcx> {
2844 let tcx = self.tcx();
2846 let result_ty = match &ast_ty.kind {
2847 hir::TyKind::Slice(ty) => tcx.mk_slice(self.ast_ty_to_ty(ty)),
2848 hir::TyKind::Ptr(mt) => {
2849 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl })
2851 hir::TyKind::Ref(region, mt) => {
2852 let r = self.ast_region_to_region(region, None);
2854 let t = self.ast_ty_to_ty_inner(mt.ty, true, false);
2855 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2857 hir::TyKind::Never => tcx.types.never,
2858 hir::TyKind::Tup(fields) => tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(t))),
2859 hir::TyKind::BareFn(bf) => {
2860 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span);
2862 tcx.mk_fn_ptr(self.ty_of_fn(
2871 hir::TyKind::TraitObject(bounds, lifetime, repr) => {
2872 self.maybe_lint_bare_trait(ast_ty, in_path);
2873 let repr = match repr {
2874 TraitObjectSyntax::Dyn | TraitObjectSyntax::None => ty::Dyn,
2875 TraitObjectSyntax::DynStar => ty::DynStar,
2877 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed, repr)
2879 hir::TyKind::Path(hir::QPath::Resolved(maybe_qself, path)) => {
2880 debug!(?maybe_qself, ?path);
2881 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2882 self.res_to_ty(opt_self_ty, path, false)
2884 &hir::TyKind::OpaqueDef(item_id, lifetimes, in_trait) => {
2885 let opaque_ty = tcx.hir().item(item_id);
2886 let def_id = item_id.owner_id.to_def_id();
2888 match opaque_ty.kind {
2889 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
2890 self.impl_trait_ty_to_ty(def_id, lifetimes, origin, in_trait)
2892 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2895 hir::TyKind::Path(hir::QPath::TypeRelative(qself, segment)) => {
2896 debug!(?qself, ?segment);
2897 let ty = self.ast_ty_to_ty_inner(qself, false, true);
2898 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, qself, segment, false)
2899 .map(|(ty, _, _)| ty)
2900 .unwrap_or_else(|_| tcx.ty_error())
2902 &hir::TyKind::Path(hir::QPath::LangItem(lang_item, span, _)) => {
2903 let def_id = tcx.require_lang_item(lang_item, Some(span));
2904 let (substs, _) = self.create_substs_for_ast_path(
2908 &hir::PathSegment::invalid(),
2909 &GenericArgs::none(),
2912 ty::BoundConstness::NotConst,
2914 EarlyBinder(tcx.at(span).type_of(def_id)).subst(tcx, substs)
2916 hir::TyKind::Array(ty, length) => {
2917 let length = match length {
2918 &hir::ArrayLen::Infer(_, span) => self.ct_infer(tcx.types.usize, None, span),
2919 hir::ArrayLen::Body(constant) => {
2920 ty::Const::from_anon_const(tcx, constant.def_id)
2924 tcx.mk_ty(ty::Array(self.ast_ty_to_ty(ty), length))
2926 hir::TyKind::Typeof(e) => {
2927 let ty_erased = tcx.type_of(e.def_id);
2928 let ty = tcx.fold_regions(ty_erased, |r, _| {
2929 if r.is_erased() { tcx.lifetimes.re_static } else { r }
2931 let span = ast_ty.span;
2932 tcx.sess.emit_err(TypeofReservedKeywordUsed {
2935 opt_sugg: Some((span, Applicability::MachineApplicable))
2936 .filter(|_| ty.is_suggestable(tcx, false)),
2941 hir::TyKind::Infer => {
2942 // Infer also appears as the type of arguments or return
2943 // values in an ExprKind::Closure, or as
2944 // the type of local variables. Both of these cases are
2945 // handled specially and will not descend into this routine.
2946 self.ty_infer(None, ast_ty.span)
2948 hir::TyKind::Err => tcx.ty_error(),
2951 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2955 #[instrument(level = "debug", skip(self), ret)]
2956 fn impl_trait_ty_to_ty(
2959 lifetimes: &[hir::GenericArg<'_>],
2960 origin: OpaqueTyOrigin,
2963 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2964 let tcx = self.tcx();
2966 let generics = tcx.generics_of(def_id);
2968 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2969 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2970 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2971 // Our own parameters are the resolved lifetimes.
2972 let GenericParamDefKind::Lifetime { .. } = param.kind else { bug!() };
2973 let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] else { bug!() };
2974 self.ast_region_to_region(lifetime, None).into()
2976 tcx.mk_param_from_def(param)
2979 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2981 if in_trait { tcx.mk_projection(def_id, substs) } else { tcx.mk_opaque(def_id, substs) }
2984 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2986 hir::TyKind::Infer if expected_ty.is_some() => {
2987 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2988 expected_ty.unwrap()
2990 _ => self.ast_ty_to_ty(ty),
2994 #[instrument(level = "debug", skip(self, hir_id, unsafety, abi, decl, generics, hir_ty), ret)]
2998 unsafety: hir::Unsafety,
3000 decl: &hir::FnDecl<'_>,
3001 generics: Option<&hir::Generics<'_>>,
3002 hir_ty: Option<&hir::Ty<'_>>,
3003 ) -> ty::PolyFnSig<'tcx> {
3004 let tcx = self.tcx();
3005 let bound_vars = tcx.late_bound_vars(hir_id);
3006 debug!(?bound_vars);
3008 // We proactively collect all the inferred type params to emit a single error per fn def.
3009 let mut visitor = HirPlaceholderCollector::default();
3010 let mut infer_replacements = vec![];
3012 if let Some(generics) = generics {
3013 walk_generics(&mut visitor, generics);
3016 let input_tys: Vec<_> = decl
3021 if let hir::TyKind::Infer = a.kind && !self.allow_ty_infer() {
3022 if let Some(suggested_ty) =
3023 self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i))
3025 infer_replacements.push((a.span, suggested_ty.to_string()));
3026 return suggested_ty;
3030 // Only visit the type looking for `_` if we didn't fix the type above
3031 visitor.visit_ty(a);
3032 self.ty_of_arg(a, None)
3036 let output_ty = match decl.output {
3037 hir::FnRetTy::Return(output) => {
3038 if let hir::TyKind::Infer = output.kind
3039 && !self.allow_ty_infer()
3040 && let Some(suggested_ty) =
3041 self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, None)
3043 infer_replacements.push((output.span, suggested_ty.to_string()));
3046 visitor.visit_ty(output);
3047 self.ast_ty_to_ty(output)
3050 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
3055 let fn_ty = tcx.mk_fn_sig(input_tys.into_iter(), output_ty, decl.c_variadic, unsafety, abi);
3056 let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
3058 if !self.allow_ty_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) {
3059 // We always collect the spans for placeholder types when evaluating `fn`s, but we
3060 // only want to emit an error complaining about them if infer types (`_`) are not
3061 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
3062 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
3064 let mut diag = crate::collect::placeholder_type_error_diag(
3068 infer_replacements.iter().map(|(s, _)| *s).collect(),
3074 if !infer_replacements.is_empty() {
3075 diag.multipart_suggestion(
3077 "try replacing `_` with the type{} in the corresponding trait method signature",
3078 rustc_errors::pluralize!(infer_replacements.len()),
3081 Applicability::MachineApplicable,
3088 // Find any late-bound regions declared in return type that do
3089 // not appear in the arguments. These are not well-formed.
3092 // for<'a> fn() -> &'a str <-- 'a is bad
3093 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
3094 let inputs = bare_fn_ty.inputs();
3095 let late_bound_in_args =
3096 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
3097 let output = bare_fn_ty.output();
3098 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
3100 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
3105 "return type references {}, which is not constrained by the fn input types",
3113 /// Given a fn_hir_id for a impl function, suggest the type that is found on the
3114 /// corresponding function in the trait that the impl implements, if it exists.
3115 /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
3116 /// corresponds to the return type.
3117 fn suggest_trait_fn_ty_for_impl_fn_infer(
3119 fn_hir_id: hir::HirId,
3120 arg_idx: Option<usize>,
3121 ) -> Option<Ty<'tcx>> {
3122 let tcx = self.tcx();
3123 let hir = tcx.hir();
3125 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
3126 hir.get(fn_hir_id) else { return None };
3127 let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(i), .. }) =
3128 hir.get_parent(fn_hir_id) else { bug!("ImplItem should have Impl parent") };
3130 let trait_ref = self.instantiate_mono_trait_ref(
3131 i.of_trait.as_ref()?,
3132 self.ast_ty_to_ty(i.self_ty),
3133 ty::BoundConstness::NotConst,
3136 let assoc = tcx.associated_items(trait_ref.def_id).find_by_name_and_kind(
3143 let fn_sig = tcx.bound_fn_sig(assoc.def_id).subst(
3145 trait_ref.substs.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3148 let ty = if let Some(arg_idx) = arg_idx { fn_sig.input(arg_idx) } else { fn_sig.output() };
3150 Some(tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), ty))
3153 #[instrument(level = "trace", skip(self, generate_err))]
3154 fn validate_late_bound_regions(
3156 constrained_regions: FxHashSet<ty::BoundRegionKind>,
3157 referenced_regions: FxHashSet<ty::BoundRegionKind>,
3158 generate_err: impl Fn(&str) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
3160 for br in referenced_regions.difference(&constrained_regions) {
3161 let br_name = match *br {
3162 ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) | ty::BrEnv => {
3163 "an anonymous lifetime".to_string()
3165 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
3168 let mut err = generate_err(&br_name);
3170 if let ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) = *br {
3171 // The only way for an anonymous lifetime to wind up
3172 // in the return type but **also** be unconstrained is
3173 // if it only appears in "associated types" in the
3174 // input. See #47511 and #62200 for examples. In this case,
3175 // though we can easily give a hint that ought to be
3178 "lifetimes appearing in an associated or opaque type are not considered constrained",
3180 err.note("consider introducing a named lifetime parameter");
3187 /// Given the bounds on an object, determines what single region bound (if any) we can
3188 /// use to summarize this type. The basic idea is that we will use the bound the user
3189 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
3190 /// for region bounds. It may be that we can derive no bound at all, in which case
3191 /// we return `None`.
3192 fn compute_object_lifetime_bound(
3195 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3196 ) -> Option<ty::Region<'tcx>> // if None, use the default
3198 let tcx = self.tcx();
3200 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
3202 // No explicit region bound specified. Therefore, examine trait
3203 // bounds and see if we can derive region bounds from those.
3204 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3206 // If there are no derived region bounds, then report back that we
3207 // can find no region bound. The caller will use the default.
3208 if derived_region_bounds.is_empty() {
3212 // If any of the derived region bounds are 'static, that is always
3214 if derived_region_bounds.iter().any(|r| r.is_static()) {
3215 return Some(tcx.lifetimes.re_static);
3218 // Determine whether there is exactly one unique region in the set
3219 // of derived region bounds. If so, use that. Otherwise, report an
3221 let r = derived_region_bounds[0];
3222 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3223 tcx.sess.emit_err(AmbiguousLifetimeBound { span });
3228 /// Make sure that we are in the condition to suggest the blanket implementation.
3229 fn maybe_lint_blanket_trait_impl(&self, self_ty: &hir::Ty<'_>, diag: &mut Diagnostic) {
3230 let tcx = self.tcx();
3231 let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
3232 if let hir::Node::Item(hir::Item {
3234 hir::ItemKind::Impl(hir::Impl {
3235 self_ty: impl_self_ty, of_trait: Some(of_trait_ref), generics, ..
3238 }) = tcx.hir().get_by_def_id(parent_id) && self_ty.hir_id == impl_self_ty.hir_id
3240 if !of_trait_ref.trait_def_id().map_or(false, |def_id| def_id.is_local()) {
3243 let of_trait_span = of_trait_ref.path.span;
3244 // make sure that we are not calling unwrap to abort during the compilation
3245 let Ok(impl_trait_name) = tcx.sess.source_map().span_to_snippet(self_ty.span) else { return; };
3246 let Ok(of_trait_name) = tcx.sess.source_map().span_to_snippet(of_trait_span) else { return; };
3247 // check if the trait has generics, to make a correct suggestion
3248 let param_name = generics.params.next_type_param_name(None);
3250 let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() {
3251 (span, format!(", {}: {}", param_name, impl_trait_name))
3253 (generics.span, format!("<{}: {}>", param_name, impl_trait_name))
3255 diag.multipart_suggestion(
3256 format!("alternatively use a blanket \
3257 implementation to implement `{of_trait_name}` for \
3258 all types that also implement `{impl_trait_name}`"),
3260 (self_ty.span, param_name),
3263 Applicability::MaybeIncorrect,
3268 fn maybe_lint_bare_trait(&self, self_ty: &hir::Ty<'_>, in_path: bool) {
3269 let tcx = self.tcx();
3270 if let hir::TyKind::TraitObject([poly_trait_ref, ..], _, TraitObjectSyntax::None) =
3273 let needs_bracket = in_path
3277 .span_to_prev_source(self_ty.span)
3279 .map_or(false, |s| s.trim_end().ends_with('<'));
3281 let is_global = poly_trait_ref.trait_ref.path.is_global();
3283 let mut sugg = Vec::from_iter([(
3284 self_ty.span.shrink_to_lo(),
3287 if needs_bracket { "<" } else { "" },
3288 if is_global { "(" } else { "" },
3292 if is_global || needs_bracket {
3294 self_ty.span.shrink_to_hi(),
3297 if is_global { ")" } else { "" },
3298 if needs_bracket { ">" } else { "" },
3303 if self_ty.span.edition() >= Edition::Edition2021 {
3304 let msg = "trait objects must include the `dyn` keyword";
3305 let label = "add `dyn` keyword before this trait";
3307 rustc_errors::struct_span_err!(tcx.sess, self_ty.span, E0782, "{}", msg);
3308 if self_ty.span.can_be_used_for_suggestions() {
3309 diag.multipart_suggestion_verbose(
3312 Applicability::MachineApplicable,
3315 // check if the impl trait that we are considering is a impl of a local trait
3316 self.maybe_lint_blanket_trait_impl(&self_ty, &mut diag);
3319 let msg = "trait objects without an explicit `dyn` are deprecated";
3320 tcx.struct_span_lint_hir(
3326 lint.multipart_suggestion_verbose(
3329 Applicability::MachineApplicable,
3331 self.maybe_lint_blanket_trait_impl(&self_ty, lint);