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_middle::middle::stability::AllowUnstable;
31 use rustc_middle::ty::subst::{self, GenericArgKind, InternalSubsts, SubstsRef};
32 use rustc_middle::ty::GenericParamDefKind;
33 use rustc_middle::ty::{self, Const, DefIdTree, IsSuggestable, Ty, TyCtxt, TypeVisitable};
34 use rustc_middle::ty::{DynKind, EarlyBinder};
35 use rustc_session::lint::builtin::{AMBIGUOUS_ASSOCIATED_ITEMS, BARE_TRAIT_OBJECTS};
36 use rustc_span::edition::Edition;
37 use rustc_span::lev_distance::find_best_match_for_name;
38 use rustc_span::symbol::{kw, Ident, Symbol};
39 use rustc_span::{sym, Span};
40 use rustc_target::spec::abi;
41 use rustc_trait_selection::traits;
42 use rustc_trait_selection::traits::astconv_object_safety_violations;
43 use rustc_trait_selection::traits::error_reporting::{
44 report_object_safety_error, suggestions::NextTypeParamName,
46 use rustc_trait_selection::traits::wf::object_region_bounds;
48 use smallvec::{smallvec, SmallVec};
49 use std::collections::BTreeSet;
53 pub struct PathSeg(pub DefId, pub usize);
55 pub trait AstConv<'tcx> {
56 fn tcx<'a>(&'a self) -> TyCtxt<'tcx>;
58 fn item_def_id(&self) -> DefId;
60 /// Returns predicates in scope of the form `X: Foo<T>`, where `X`
61 /// is a type parameter `X` with the given id `def_id` and T
62 /// matches `assoc_name`. This is a subset of the full set of
65 /// This is used for one specific purpose: resolving "short-hand"
66 /// associated type references like `T::Item`. In principle, we
67 /// would do that by first getting the full set of predicates in
68 /// scope and then filtering down to find those that apply to `T`,
69 /// but this can lead to cycle errors. The problem is that we have
70 /// to do this resolution *in order to create the predicates in
71 /// the first place*. Hence, we have this "special pass".
72 fn get_type_parameter_bounds(
77 ) -> ty::GenericPredicates<'tcx>;
79 /// Returns the lifetime to use when a lifetime is omitted (and not elided).
80 fn re_infer(&self, param: Option<&ty::GenericParamDef>, span: Span)
81 -> Option<ty::Region<'tcx>>;
83 /// Returns the type to use when a type is omitted.
84 fn ty_infer(&self, param: Option<&ty::GenericParamDef>, span: Span) -> Ty<'tcx>;
86 /// Returns `true` if `_` is allowed in type signatures in the current context.
87 fn allow_ty_infer(&self) -> bool;
89 /// Returns the const to use when a const is omitted.
93 param: Option<&ty::GenericParamDef>,
97 /// Projecting an associated type from a (potentially)
98 /// higher-ranked trait reference is more complicated, because of
99 /// the possibility of late-bound regions appearing in the
100 /// associated type binding. This is not legal in function
101 /// signatures for that reason. In a function body, we can always
102 /// handle it because we can use inference variables to remove the
103 /// late-bound regions.
104 fn projected_ty_from_poly_trait_ref(
108 item_segment: &hir::PathSegment<'_>,
109 poly_trait_ref: ty::PolyTraitRef<'tcx>,
112 /// Returns `AdtDef` if `ty` is an ADT.
113 /// Note that `ty` might be a projection type that needs normalization.
114 /// This used to get the enum variants in scope of the type.
115 /// For example, `Self::A` could refer to an associated type
116 /// or to an enum variant depending on the result of this function.
117 fn probe_adt(&self, span: Span, ty: Ty<'tcx>) -> Option<ty::AdtDef<'tcx>>;
119 /// Invoked when we encounter an error from some prior pass
120 /// (e.g., resolve) that is translated into a ty-error. This is
121 /// used to help suppress derived errors typeck might otherwise
123 fn set_tainted_by_errors(&self, e: ErrorGuaranteed);
125 fn record_ty(&self, hir_id: hir::HirId, ty: Ty<'tcx>, span: Span);
127 fn astconv(&self) -> &dyn AstConv<'tcx>
136 struct ConvertedBinding<'a, 'tcx> {
139 kind: ConvertedBindingKind<'a, 'tcx>,
140 gen_args: &'a GenericArgs<'a>,
145 enum ConvertedBindingKind<'a, 'tcx> {
146 Equality(ty::Term<'tcx>),
147 Constraint(&'a [hir::GenericBound<'a>]),
150 /// New-typed boolean indicating whether explicit late-bound lifetimes
151 /// are present in a set of generic arguments.
153 /// For example if we have some method `fn f<'a>(&'a self)` implemented
154 /// for some type `T`, although `f` is generic in the lifetime `'a`, `'a`
155 /// is late-bound so should not be provided explicitly. Thus, if `f` is
156 /// instantiated with some generic arguments providing `'a` explicitly,
157 /// we taint those arguments with `ExplicitLateBound::Yes` so that we
158 /// can provide an appropriate diagnostic later.
159 #[derive(Copy, Clone, PartialEq, Debug)]
160 pub enum ExplicitLateBound {
165 #[derive(Copy, Clone, PartialEq)]
166 pub enum IsMethodCall {
171 /// Denotes the "position" of a generic argument, indicating if it is a generic type,
172 /// generic function or generic method call.
173 #[derive(Copy, Clone, PartialEq)]
174 pub(crate) enum GenericArgPosition {
176 Value, // e.g., functions
180 /// A marker denoting that the generic arguments that were
181 /// provided did not match the respective generic parameters.
182 #[derive(Clone, Default, Debug)]
183 pub struct GenericArgCountMismatch {
184 /// Indicates whether a fatal error was reported (`Some`), or just a lint (`None`).
185 pub reported: Option<ErrorGuaranteed>,
186 /// A list of spans of arguments provided that were not valid.
187 pub invalid_args: Vec<Span>,
190 /// Decorates the result of a generic argument count mismatch
191 /// check with whether explicit late bounds were provided.
192 #[derive(Clone, Debug)]
193 pub struct GenericArgCountResult {
194 pub explicit_late_bound: ExplicitLateBound,
195 pub correct: Result<(), GenericArgCountMismatch>,
198 pub trait CreateSubstsForGenericArgsCtxt<'a, 'tcx> {
199 fn args_for_def_id(&mut self, def_id: DefId) -> (Option<&'a GenericArgs<'a>>, bool);
203 param: &ty::GenericParamDef,
204 arg: &GenericArg<'_>,
205 ) -> subst::GenericArg<'tcx>;
209 substs: Option<&[subst::GenericArg<'tcx>]>,
210 param: &ty::GenericParamDef,
212 ) -> subst::GenericArg<'tcx>;
215 impl<'o, 'tcx> dyn AstConv<'tcx> + 'o {
216 #[instrument(level = "debug", skip(self), ret)]
217 pub fn ast_region_to_region(
219 lifetime: &hir::Lifetime,
220 def: Option<&ty::GenericParamDef>,
221 ) -> ty::Region<'tcx> {
222 let tcx = self.tcx();
223 let lifetime_name = |def_id| tcx.hir().name(tcx.hir().local_def_id_to_hir_id(def_id));
225 match tcx.named_region(lifetime.hir_id) {
226 Some(rl::Region::Static) => tcx.lifetimes.re_static,
228 Some(rl::Region::LateBound(debruijn, index, def_id)) => {
229 let name = lifetime_name(def_id.expect_local());
230 let br = ty::BoundRegion {
231 var: ty::BoundVar::from_u32(index),
232 kind: ty::BrNamed(def_id, name),
234 tcx.mk_region(ty::ReLateBound(debruijn, br))
237 Some(rl::Region::EarlyBound(def_id)) => {
238 let name = tcx.hir().ty_param_name(def_id.expect_local());
239 let item_def_id = tcx.hir().ty_param_owner(def_id.expect_local());
240 let generics = tcx.generics_of(item_def_id);
241 let index = generics.param_def_id_to_index[&def_id];
242 tcx.mk_region(ty::ReEarlyBound(ty::EarlyBoundRegion { def_id, index, name }))
245 Some(rl::Region::Free(scope, id)) => {
246 let name = lifetime_name(id.expect_local());
247 tcx.mk_region(ty::ReFree(ty::FreeRegion {
249 bound_region: ty::BrNamed(id, name),
252 // (*) -- not late-bound, won't change
256 self.re_infer(def, lifetime.ident.span).unwrap_or_else(|| {
257 debug!(?lifetime, "unelided lifetime in signature");
259 // This indicates an illegal lifetime
260 // elision. `resolve_lifetime` should have
261 // reported an error in this case -- but if
262 // not, let's error out.
263 tcx.sess.delay_span_bug(lifetime.ident.span, "unelided lifetime in signature");
265 // Supply some dummy value. We don't have an
266 // `re_error`, annoyingly, so use `'static`.
267 tcx.lifetimes.re_static
273 /// Given a path `path` that refers to an item `I` with the declared generics `decl_generics`,
274 /// returns an appropriate set of substitutions for this particular reference to `I`.
275 pub fn ast_path_substs_for_ty(
279 item_segment: &hir::PathSegment<'_>,
280 ) -> SubstsRef<'tcx> {
281 let (substs, _) = self.create_substs_for_ast_path(
287 item_segment.infer_args,
289 ty::BoundConstness::NotConst,
291 if let Some(b) = item_segment.args().bindings.first() {
292 prohibit_assoc_ty_binding(self.tcx(), b.span);
298 /// Given the type/lifetime/const arguments provided to some path (along with
299 /// an implicit `Self`, if this is a trait reference), returns the complete
300 /// set of substitutions. This may involve applying defaulted type parameters.
301 /// Constraints on associated types are created from `create_assoc_bindings_for_generic_args`.
305 /// ```ignore (illustrative)
306 /// T: std::ops::Index<usize, Output = u32>
307 /// // ^1 ^^^^^^^^^^^^^^2 ^^^^3 ^^^^^^^^^^^4
310 /// 1. The `self_ty` here would refer to the type `T`.
311 /// 2. The path in question is the path to the trait `std::ops::Index`,
312 /// which will have been resolved to a `def_id`
313 /// 3. The `generic_args` contains info on the `<...>` contents. The `usize` type
314 /// parameters are returned in the `SubstsRef`, the associated type bindings like
315 /// `Output = u32` are returned from `create_assoc_bindings_for_generic_args`.
317 /// Note that the type listing given here is *exactly* what the user provided.
319 /// For (generic) associated types
321 /// ```ignore (illustrative)
322 /// <Vec<u8> as Iterable<u8>>::Iter::<'a>
325 /// We have the parent substs are the substs for the parent trait:
326 /// `[Vec<u8>, u8]` and `generic_args` are the arguments for the associated
327 /// type itself: `['a]`. The returned `SubstsRef` concatenates these two
328 /// lists: `[Vec<u8>, u8, 'a]`.
329 #[instrument(level = "debug", skip(self, span), ret)]
330 fn create_substs_for_ast_path<'a>(
334 parent_substs: &[subst::GenericArg<'tcx>],
335 seg: &hir::PathSegment<'_>,
336 generic_args: &'a hir::GenericArgs<'_>,
338 self_ty: Option<Ty<'tcx>>,
339 constness: ty::BoundConstness,
340 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
341 // If the type is parameterized by this region, then replace this
342 // region with the current anon region binding (in other words,
343 // whatever & would get replaced with).
345 let tcx = self.tcx();
346 let generics = tcx.generics_of(def_id);
347 debug!("generics: {:?}", generics);
349 if generics.has_self {
350 if generics.parent.is_some() {
351 // The parent is a trait so it should have at least one subst
352 // for the `Self` type.
353 assert!(!parent_substs.is_empty())
355 // This item (presumably a trait) needs a self-type.
356 assert!(self_ty.is_some());
359 assert!(self_ty.is_none());
362 let arg_count = check_generic_arg_count(
369 GenericArgPosition::Type,
374 // Skip processing if type has no generic parameters.
375 // Traits always have `Self` as a generic parameter, which means they will not return early
376 // here and so associated type bindings will be handled regardless of whether there are any
377 // non-`Self` generic parameters.
378 if generics.params.is_empty() {
379 return (tcx.intern_substs(parent_substs), arg_count);
382 struct SubstsForAstPathCtxt<'a, 'tcx> {
383 astconv: &'a (dyn AstConv<'tcx> + 'a),
385 generic_args: &'a GenericArgs<'a>,
387 inferred_params: Vec<Span>,
391 impl<'a, 'tcx> CreateSubstsForGenericArgsCtxt<'a, 'tcx> for SubstsForAstPathCtxt<'a, 'tcx> {
392 fn args_for_def_id(&mut self, did: DefId) -> (Option<&'a GenericArgs<'a>>, bool) {
393 if did == self.def_id {
394 (Some(self.generic_args), self.infer_args)
396 // The last component of this tuple is unimportant.
403 param: &ty::GenericParamDef,
404 arg: &GenericArg<'_>,
405 ) -> subst::GenericArg<'tcx> {
406 let tcx = self.astconv.tcx();
408 let mut handle_ty_args = |has_default, ty: &hir::Ty<'_>| {
410 tcx.check_optional_stability(
417 // Default generic parameters may not be marked
418 // with stability attributes, i.e. when the
419 // default parameter was defined at the same time
420 // as the rest of the type. As such, we ignore missing
421 // stability attributes.
425 if let (hir::TyKind::Infer, false) = (&ty.kind, self.astconv.allow_ty_infer()) {
426 self.inferred_params.push(ty.span);
427 tcx.ty_error().into()
429 self.astconv.ast_ty_to_ty(ty).into()
433 match (¶m.kind, arg) {
434 (GenericParamDefKind::Lifetime, GenericArg::Lifetime(lt)) => {
435 self.astconv.ast_region_to_region(lt, Some(param)).into()
437 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Type(ty)) => {
438 handle_ty_args(has_default, ty)
440 (&GenericParamDefKind::Type { has_default, .. }, GenericArg::Infer(inf)) => {
441 handle_ty_args(has_default, &inf.to_ty())
443 (GenericParamDefKind::Const { .. }, GenericArg::Const(ct)) => {
444 ty::Const::from_opt_const_arg_anon_const(
446 ty::WithOptConstParam {
447 did: ct.value.def_id,
448 const_param_did: Some(param.def_id),
453 (&GenericParamDefKind::Const { .. }, hir::GenericArg::Infer(inf)) => {
454 let ty = tcx.at(self.span).type_of(param.def_id);
455 if self.astconv.allow_ty_infer() {
456 self.astconv.ct_infer(ty, Some(param), inf.span).into()
458 self.inferred_params.push(inf.span);
459 tcx.const_error(ty).into()
468 substs: Option<&[subst::GenericArg<'tcx>]>,
469 param: &ty::GenericParamDef,
471 ) -> subst::GenericArg<'tcx> {
472 let tcx = self.astconv.tcx();
474 GenericParamDefKind::Lifetime => self
476 .re_infer(Some(param), self.span)
478 debug!(?param, "unelided lifetime in signature");
480 // This indicates an illegal lifetime in a non-assoc-trait position
481 tcx.sess.delay_span_bug(self.span, "unelided lifetime in signature");
483 // Supply some dummy value. We don't have an
484 // `re_error`, annoyingly, so use `'static`.
485 tcx.lifetimes.re_static
488 GenericParamDefKind::Type { has_default, .. } => {
489 if !infer_args && has_default {
490 // No type parameter provided, but a default exists.
491 let substs = substs.unwrap();
492 if substs.iter().any(|arg| match arg.unpack() {
493 GenericArgKind::Type(ty) => ty.references_error(),
496 // Avoid ICE #86756 when type error recovery goes awry.
497 return tcx.ty_error().into();
499 tcx.at(self.span).bound_type_of(param.def_id).subst(tcx, substs).into()
500 } else if infer_args {
501 self.astconv.ty_infer(Some(param), self.span).into()
503 // We've already errored above about the mismatch.
504 tcx.ty_error().into()
507 GenericParamDefKind::Const { has_default } => {
508 let ty = tcx.at(self.span).type_of(param.def_id);
509 if ty.references_error() {
510 return tcx.const_error(ty).into();
512 if !infer_args && has_default {
513 tcx.bound_const_param_default(param.def_id)
514 .subst(tcx, substs.unwrap())
518 self.astconv.ct_infer(ty, Some(param), self.span).into()
520 // We've already errored above about the mismatch.
521 tcx.const_error(ty).into()
529 let mut substs_ctx = SubstsForAstPathCtxt {
534 inferred_params: vec![],
537 let substs = create_substs_for_generic_args(
547 if let ty::BoundConstness::ConstIfConst = constness
548 && generics.has_self && !tcx.has_attr(def_id, sym::const_trait)
550 tcx.sess.emit_err(crate::errors::ConstBoundForNonConstTrait { span } );
556 fn create_assoc_bindings_for_generic_args<'a>(
558 generic_args: &'a hir::GenericArgs<'_>,
559 ) -> Vec<ConvertedBinding<'a, 'tcx>> {
560 // Convert associated-type bindings or constraints into a separate vector.
561 // Example: Given this:
563 // T: Iterator<Item = u32>
565 // The `T` is passed in as a self-type; the `Item = u32` is
566 // not a "type parameter" of the `Iterator` trait, but rather
567 // a restriction on `<T as Iterator>::Item`, so it is passed
569 let assoc_bindings = generic_args
573 let kind = match binding.kind {
574 hir::TypeBindingKind::Equality { ref term } => match term {
575 hir::Term::Ty(ref ty) => {
576 ConvertedBindingKind::Equality(self.ast_ty_to_ty(ty).into())
578 hir::Term::Const(ref c) => {
579 let c = Const::from_anon_const(self.tcx(), c.def_id);
580 ConvertedBindingKind::Equality(c.into())
583 hir::TypeBindingKind::Constraint { ref bounds } => {
584 ConvertedBindingKind::Constraint(bounds)
588 hir_id: binding.hir_id,
589 item_name: binding.ident,
591 gen_args: binding.gen_args,
600 pub fn create_substs_for_associated_item(
604 item_segment: &hir::PathSegment<'_>,
605 parent_substs: SubstsRef<'tcx>,
606 ) -> SubstsRef<'tcx> {
608 "create_substs_for_associated_item(span: {:?}, item_def_id: {:?}, item_segment: {:?}",
609 span, item_def_id, item_segment
611 let (args, _) = self.create_substs_for_ast_path(
617 item_segment.infer_args,
619 ty::BoundConstness::NotConst,
622 if let Some(b) = item_segment.args().bindings.first() {
623 prohibit_assoc_ty_binding(self.tcx(), b.span);
629 /// Instantiates the path for the given trait reference, assuming that it's
630 /// bound to a valid trait type. Returns the `DefId` of the defining trait.
631 /// The type _cannot_ be a type other than a trait type.
633 /// If the `projections` argument is `None`, then assoc type bindings like `Foo<T = X>`
634 /// are disallowed. Otherwise, they are pushed onto the vector given.
635 pub fn instantiate_mono_trait_ref(
637 trait_ref: &hir::TraitRef<'_>,
639 constness: ty::BoundConstness,
640 ) -> ty::TraitRef<'tcx> {
641 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
643 self.ast_path_to_mono_trait_ref(
645 trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
647 trait_ref.path.segments.last().unwrap(),
653 fn instantiate_poly_trait_ref_inner(
657 binding_span: Option<Span>,
658 constness: ty::BoundConstness,
659 bounds: &mut Bounds<'tcx>,
661 trait_ref_span: Span,
663 trait_segment: &hir::PathSegment<'_>,
664 args: &GenericArgs<'_>,
667 ) -> GenericArgCountResult {
668 let (substs, arg_count) = self.create_substs_for_ast_path(
679 let tcx = self.tcx();
680 let bound_vars = tcx.late_bound_vars(hir_id);
683 let assoc_bindings = self.create_assoc_bindings_for_generic_args(args);
686 ty::Binder::bind_with_vars(tcx.mk_trait_ref(trait_def_id, substs), bound_vars);
688 debug!(?poly_trait_ref, ?assoc_bindings);
689 bounds.push_trait_bound(tcx, poly_trait_ref, span, constness);
691 let mut dup_bindings = FxHashMap::default();
692 for binding in &assoc_bindings {
693 // Specify type to assert that error was already reported in `Err` case.
694 let _: Result<_, ErrorGuaranteed> = self.add_predicates_for_ast_type_binding(
701 binding_span.unwrap_or(binding.span),
704 // Okay to ignore `Err` because of `ErrorGuaranteed` (see above).
710 /// Given a trait bound like `Debug`, applies that trait bound the given self-type to construct
711 /// a full trait reference. The resulting trait reference is returned. This may also generate
712 /// auxiliary bounds, which are added to `bounds`.
716 /// ```ignore (illustrative)
717 /// poly_trait_ref = Iterator<Item = u32>
721 /// this would return `Foo: Iterator` and add `<Foo as Iterator>::Item = u32` into `bounds`.
723 /// **A note on binders:** against our usual convention, there is an implied bounder around
724 /// the `self_ty` and `poly_trait_ref` parameters here. So they may reference bound regions.
725 /// If for example you had `for<'a> Foo<'a>: Bar<'a>`, then the `self_ty` would be `Foo<'a>`
726 /// where `'a` is a bound region at depth 0. Similarly, the `poly_trait_ref` would be
727 /// `Bar<'a>`. The returned poly-trait-ref will have this binder instantiated explicitly,
729 #[instrument(level = "debug", skip(self, span, constness, bounds, speculative))]
730 pub(crate) fn instantiate_poly_trait_ref(
732 trait_ref: &hir::TraitRef<'_>,
734 constness: ty::BoundConstness,
736 bounds: &mut Bounds<'tcx>,
738 ) -> GenericArgCountResult {
739 let hir_id = trait_ref.hir_ref_id;
740 let binding_span = None;
741 let trait_ref_span = trait_ref.path.span;
742 let trait_def_id = trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise());
743 let trait_segment = trait_ref.path.segments.last().unwrap();
744 let args = trait_segment.args();
745 let infer_args = trait_segment.infer_args;
747 self.prohibit_generics(trait_ref.path.segments.split_last().unwrap().1.iter(), |_| {});
748 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, false);
750 self.instantiate_poly_trait_ref_inner(
766 pub(crate) fn instantiate_lang_item_trait_ref(
768 lang_item: hir::LangItem,
771 args: &GenericArgs<'_>,
773 bounds: &mut Bounds<'tcx>,
775 let binding_span = Some(span);
776 let constness = ty::BoundConstness::NotConst;
777 let speculative = false;
778 let trait_ref_span = span;
779 let trait_def_id = self.tcx().require_lang_item(lang_item, Some(span));
780 let trait_segment = &hir::PathSegment::invalid();
781 let infer_args = false;
783 self.instantiate_poly_trait_ref_inner(
799 fn ast_path_to_mono_trait_ref(
804 trait_segment: &hir::PathSegment<'_>,
806 constness: ty::BoundConstness,
807 ) -> ty::TraitRef<'tcx> {
808 let (substs, _) = self.create_substs_for_ast_trait_ref(
816 if let Some(b) = trait_segment.args().bindings.first() {
817 prohibit_assoc_ty_binding(self.tcx(), b.span);
819 self.tcx().mk_trait_ref(trait_def_id, substs)
822 #[instrument(level = "debug", skip(self, span))]
823 fn create_substs_for_ast_trait_ref<'a>(
828 trait_segment: &'a hir::PathSegment<'a>,
830 constness: ty::BoundConstness,
831 ) -> (SubstsRef<'tcx>, GenericArgCountResult) {
832 self.complain_about_internal_fn_trait(span, trait_def_id, trait_segment, is_impl);
834 self.create_substs_for_ast_path(
839 trait_segment.args(),
840 trait_segment.infer_args,
846 fn trait_defines_associated_type_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
848 .associated_items(trait_def_id)
849 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, trait_def_id)
852 fn trait_defines_associated_const_named(&self, trait_def_id: DefId, assoc_name: Ident) -> bool {
854 .associated_items(trait_def_id)
855 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Const, trait_def_id)
859 /// Sets `implicitly_sized` to true on `Bounds` if necessary
860 pub(crate) fn add_implicitly_sized(
862 bounds: &mut Bounds<'tcx>,
864 ast_bounds: &'tcx [hir::GenericBound<'tcx>],
865 self_ty_where_predicates: Option<(LocalDefId, &'tcx [hir::WherePredicate<'tcx>])>,
868 let tcx = self.tcx();
870 // Try to find an unbound in bounds.
871 let mut unbound = None;
872 let mut search_bounds = |ast_bounds: &'tcx [hir::GenericBound<'tcx>]| {
873 for ab in ast_bounds {
874 if let hir::GenericBound::Trait(ptr, hir::TraitBoundModifier::Maybe) = ab {
875 if unbound.is_none() {
876 unbound = Some(&ptr.trait_ref);
878 tcx.sess.emit_err(MultipleRelaxedDefaultBounds { span });
883 search_bounds(ast_bounds);
884 if let Some((self_ty, where_clause)) = self_ty_where_predicates {
885 for clause in where_clause {
886 if let hir::WherePredicate::BoundPredicate(pred) = clause {
887 if pred.is_param_bound(self_ty.to_def_id()) {
888 search_bounds(pred.bounds);
894 let sized_def_id = tcx.lang_items().sized_trait();
895 match (&sized_def_id, unbound) {
896 (Some(sized_def_id), Some(tpb))
897 if tpb.path.res == Res::Def(DefKind::Trait, *sized_def_id) =>
899 // There was in fact a `?Sized` bound, return without doing anything
903 // There was a `?Trait` bound, but it was not `?Sized`; warn.
906 "default bound relaxed for a type parameter, but \
907 this does nothing because the given bound is not \
908 a default; only `?Sized` is supported",
910 // Otherwise, add implicitly sized if `Sized` is available.
913 // There was no `?Sized` bound; add implicitly sized if `Sized` is available.
916 if sized_def_id.is_none() {
917 // No lang item for `Sized`, so we can't add it as a bound.
920 bounds.push_sized(tcx, self_ty, span);
923 /// This helper takes a *converted* parameter type (`param_ty`)
924 /// and an *unconverted* list of bounds:
928 /// ^ ^^^^^ `ast_bounds` parameter, in HIR form
930 /// `param_ty`, in ty form
933 /// It adds these `ast_bounds` into the `bounds` structure.
935 /// **A note on binders:** there is an implied binder around
936 /// `param_ty` and `ast_bounds`. See `instantiate_poly_trait_ref`
937 /// for more details.
938 #[instrument(level = "debug", skip(self, ast_bounds, bounds))]
939 pub(crate) fn add_bounds<'hir, I: Iterator<Item = &'hir hir::GenericBound<'hir>>>(
943 bounds: &mut Bounds<'tcx>,
944 bound_vars: &'tcx ty::List<ty::BoundVariableKind>,
946 for ast_bound in ast_bounds {
948 hir::GenericBound::Trait(poly_trait_ref, modifier) => {
949 let constness = match modifier {
950 hir::TraitBoundModifier::MaybeConst => ty::BoundConstness::ConstIfConst,
951 hir::TraitBoundModifier::None => ty::BoundConstness::NotConst,
952 hir::TraitBoundModifier::Maybe => continue,
955 let _ = self.instantiate_poly_trait_ref(
956 &poly_trait_ref.trait_ref,
964 &hir::GenericBound::LangItemTrait(lang_item, span, hir_id, args) => {
965 self.instantiate_lang_item_trait_ref(
966 lang_item, span, hir_id, args, param_ty, bounds,
969 hir::GenericBound::Outlives(lifetime) => {
970 let region = self.ast_region_to_region(lifetime, None);
971 bounds.push_region_bound(
973 ty::Binder::bind_with_vars(
974 ty::OutlivesPredicate(param_ty, region),
984 /// Translates a list of bounds from the HIR into the `Bounds` data structure.
985 /// The self-type for the bounds is given by `param_ty`.
989 /// ```ignore (illustrative)
990 /// fn foo<T: Bar + Baz>() { }
991 /// // ^ ^^^^^^^^^ ast_bounds
995 /// The `sized_by_default` parameter indicates if, in this context, the `param_ty` should be
996 /// considered `Sized` unless there is an explicit `?Sized` bound. This would be true in the
997 /// example above, but is not true in supertrait listings like `trait Foo: Bar + Baz`.
999 /// `span` should be the declaration size of the parameter.
1000 pub(crate) fn compute_bounds(
1003 ast_bounds: &[hir::GenericBound<'_>],
1005 self.compute_bounds_inner(param_ty, ast_bounds)
1008 /// Convert the bounds in `ast_bounds` that refer to traits which define an associated type
1009 /// named `assoc_name` into ty::Bounds. Ignore the rest.
1010 pub(crate) fn compute_bounds_that_match_assoc_type(
1013 ast_bounds: &[hir::GenericBound<'_>],
1016 let mut result = Vec::new();
1018 for ast_bound in ast_bounds {
1019 if let Some(trait_ref) = ast_bound.trait_ref()
1020 && let Some(trait_did) = trait_ref.trait_def_id()
1021 && self.tcx().trait_may_define_assoc_type(trait_did, assoc_name)
1023 result.push(ast_bound.clone());
1027 self.compute_bounds_inner(param_ty, &result)
1030 fn compute_bounds_inner(
1033 ast_bounds: &[hir::GenericBound<'_>],
1035 let mut bounds = Bounds::default();
1037 self.add_bounds(param_ty, ast_bounds.iter(), &mut bounds, ty::List::empty());
1043 /// Given an HIR binding like `Item = Foo` or `Item: Foo`, pushes the corresponding predicates
1046 /// **A note on binders:** given something like `T: for<'a> Iterator<Item = &'a u32>`, the
1047 /// `trait_ref` here will be `for<'a> T: Iterator`. The `binding` data however is from *inside*
1048 /// the binder (e.g., `&'a u32`) and hence may reference bound regions.
1049 #[instrument(level = "debug", skip(self, bounds, speculative, dup_bindings, path_span))]
1050 fn add_predicates_for_ast_type_binding(
1052 hir_ref_id: hir::HirId,
1053 trait_ref: ty::PolyTraitRef<'tcx>,
1054 binding: &ConvertedBinding<'_, 'tcx>,
1055 bounds: &mut Bounds<'tcx>,
1057 dup_bindings: &mut FxHashMap<DefId, Span>,
1059 constness: ty::BoundConstness,
1060 ) -> Result<(), ErrorGuaranteed> {
1061 // Given something like `U: SomeTrait<T = X>`, we want to produce a
1062 // predicate like `<U as SomeTrait>::T = X`. This is somewhat
1063 // subtle in the event that `T` is defined in a supertrait of
1064 // `SomeTrait`, because in that case we need to upcast.
1066 // That is, consider this case:
1069 // trait SubTrait: SuperTrait<i32> { }
1070 // trait SuperTrait<A> { type T; }
1072 // ... B: SubTrait<T = foo> ...
1075 // We want to produce `<B as SuperTrait<i32>>::T == foo`.
1077 let tcx = self.tcx();
1080 if self.trait_defines_associated_type_named(trait_ref.def_id(), binding.item_name) {
1081 // Simple case: X is defined in the current trait.
1084 // Otherwise, we have to walk through the supertraits to find
1086 self.one_bound_for_assoc_type(
1087 || traits::supertraits(tcx, trait_ref),
1088 || trait_ref.print_only_trait_path().to_string(),
1091 || match binding.kind {
1092 ConvertedBindingKind::Equality(ty) => Some(ty.to_string()),
1098 let (assoc_ident, def_scope) =
1099 tcx.adjust_ident_and_get_scope(binding.item_name, candidate.def_id(), hir_ref_id);
1101 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
1102 // of calling `filter_by_name_and_kind`.
1103 let find_item_of_kind = |kind| {
1104 tcx.associated_items(candidate.def_id())
1105 .filter_by_name_unhygienic(assoc_ident.name)
1106 .find(|i| i.kind == kind && i.ident(tcx).normalize_to_macros_2_0() == assoc_ident)
1108 let assoc_item = find_item_of_kind(ty::AssocKind::Type)
1109 .or_else(|| find_item_of_kind(ty::AssocKind::Const))
1110 .expect("missing associated type");
1112 if !assoc_item.visibility(tcx).is_accessible_from(def_scope, tcx) {
1116 &format!("{} `{}` is private", assoc_item.kind, binding.item_name),
1118 .span_label(binding.span, &format!("private {}", assoc_item.kind))
1121 tcx.check_stability(assoc_item.def_id, Some(hir_ref_id), binding.span, None);
1125 .entry(assoc_item.def_id)
1126 .and_modify(|prev_span| {
1127 self.tcx().sess.emit_err(ValueOfAssociatedStructAlreadySpecified {
1129 prev_span: *prev_span,
1130 item_name: binding.item_name,
1131 def_path: tcx.def_path_str(assoc_item.container_id(tcx)),
1134 .or_insert(binding.span);
1137 // Include substitutions for generic parameters of associated types
1138 let projection_ty = candidate.map_bound(|trait_ref| {
1139 let ident = Ident::new(assoc_item.name, binding.item_name.span);
1140 let item_segment = hir::PathSegment {
1142 hir_id: binding.hir_id,
1144 args: Some(binding.gen_args),
1148 let substs_trait_ref_and_assoc_item = self.create_substs_for_associated_item(
1155 debug!(?substs_trait_ref_and_assoc_item);
1157 self.tcx().mk_alias_ty(assoc_item.def_id, substs_trait_ref_and_assoc_item)
1161 // Find any late-bound regions declared in `ty` that are not
1162 // declared in the trait-ref or assoc_item. These are not well-formed.
1166 // for<'a> <T as Iterator>::Item = &'a str // <-- 'a is bad
1167 // for<'a> <T as FnMut<(&'a u32,)>>::Output = &'a str // <-- 'a is ok
1168 if let ConvertedBindingKind::Equality(ty) = binding.kind {
1169 let late_bound_in_trait_ref =
1170 tcx.collect_constrained_late_bound_regions(&projection_ty);
1171 let late_bound_in_ty =
1172 tcx.collect_referenced_late_bound_regions(&trait_ref.rebind(ty));
1173 debug!(?late_bound_in_trait_ref);
1174 debug!(?late_bound_in_ty);
1176 // FIXME: point at the type params that don't have appropriate lifetimes:
1177 // struct S1<F: for<'a> Fn(&i32, &i32) -> &'a i32>(F);
1178 // ---- ---- ^^^^^^^
1179 self.validate_late_bound_regions(
1180 late_bound_in_trait_ref,
1187 "binding for associated type `{}` references {}, \
1188 which does not appear in the trait input types",
1197 match binding.kind {
1198 ConvertedBindingKind::Equality(mut term) => {
1199 // "Desugar" a constraint like `T: Iterator<Item = u32>` this to
1200 // the "projection predicate" for:
1202 // `<T as Iterator>::Item = u32`
1203 let assoc_item_def_id = projection_ty.skip_binder().def_id;
1204 let def_kind = tcx.def_kind(assoc_item_def_id);
1205 match (def_kind, term.unpack()) {
1206 (hir::def::DefKind::AssocTy, ty::TermKind::Ty(_))
1207 | (hir::def::DefKind::AssocConst, ty::TermKind::Const(_)) => (),
1209 let got = if let Some(_) = term.ty() { "type" } else { "constant" };
1210 let expected = def_kind.descr(assoc_item_def_id);
1211 let mut err = tcx.sess.struct_span_err(
1213 &format!("expected {expected} bound, found {got}"),
1216 tcx.def_span(assoc_item_def_id),
1217 &format!("{expected} defined here"),
1220 if let hir::def::DefKind::AssocConst = def_kind
1221 && let Some(t) = term.ty() && (t.is_enum() || t.references_error())
1222 && tcx.features().associated_const_equality {
1223 err.span_suggestion(
1225 "if equating a const, try wrapping with braces",
1226 format!("{} = {{ const }}", binding.item_name),
1227 Applicability::HasPlaceholders,
1230 let reported = err.emit();
1231 term = match def_kind {
1232 hir::def::DefKind::AssocTy => {
1233 tcx.ty_error_with_guaranteed(reported).into()
1235 hir::def::DefKind::AssocConst => tcx
1236 .const_error_with_guaranteed(
1237 tcx.bound_type_of(assoc_item_def_id)
1238 .subst(tcx, projection_ty.skip_binder().substs),
1242 _ => unreachable!(),
1246 bounds.push_projection_bound(
1249 .map_bound(|projection_ty| ty::ProjectionPredicate { projection_ty, term }),
1253 ConvertedBindingKind::Constraint(ast_bounds) => {
1254 // "Desugar" a constraint like `T: Iterator<Item: Debug>` to
1256 // `<T as Iterator>::Item: Debug`
1258 // Calling `skip_binder` is okay, because `add_bounds` expects the `param_ty`
1259 // parameter to have a skipped binder.
1260 let param_ty = tcx.mk_ty(ty::Alias(ty::Projection, projection_ty.skip_binder()));
1261 self.add_bounds(param_ty, ast_bounds.iter(), bounds, candidate.bound_vars());
1271 item_segment: &hir::PathSegment<'_>,
1273 let substs = self.ast_path_substs_for_ty(span, did, item_segment);
1274 self.tcx().at(span).bound_type_of(did).subst(self.tcx(), substs)
1277 fn conv_object_ty_poly_trait_ref(
1280 hir_trait_bounds: &[hir::PolyTraitRef<'_>],
1281 lifetime: &hir::Lifetime,
1283 representation: DynKind,
1285 let tcx = self.tcx();
1287 let mut bounds = Bounds::default();
1288 let mut potential_assoc_types = Vec::new();
1289 let dummy_self = self.tcx().types.trait_object_dummy_self;
1290 for trait_bound in hir_trait_bounds.iter().rev() {
1291 if let GenericArgCountResult {
1293 Err(GenericArgCountMismatch { invalid_args: cur_potential_assoc_types, .. }),
1295 } = self.instantiate_poly_trait_ref(
1296 &trait_bound.trait_ref,
1298 ty::BoundConstness::NotConst,
1303 potential_assoc_types.extend(cur_potential_assoc_types);
1307 let mut trait_bounds = vec![];
1308 let mut projection_bounds = vec![];
1309 for (pred, span) in bounds.predicates() {
1310 let bound_pred = pred.kind();
1311 match bound_pred.skip_binder() {
1312 ty::PredicateKind::Clause(clause) => match clause {
1313 ty::Clause::Trait(trait_pred) => {
1314 assert_eq!(trait_pred.polarity, ty::ImplPolarity::Positive);
1316 bound_pred.rebind(trait_pred.trait_ref),
1318 trait_pred.constness,
1321 ty::Clause::Projection(proj) => {
1322 projection_bounds.push((bound_pred.rebind(proj), span));
1324 ty::Clause::TypeOutlives(_) => {
1325 // Do nothing, we deal with regions separately
1327 ty::Clause::RegionOutlives(_) => bug!(),
1329 ty::PredicateKind::WellFormed(_)
1330 | ty::PredicateKind::ObjectSafe(_)
1331 | ty::PredicateKind::ClosureKind(_, _, _)
1332 | ty::PredicateKind::Subtype(_)
1333 | ty::PredicateKind::Coerce(_)
1334 | ty::PredicateKind::ConstEvaluatable(_)
1335 | ty::PredicateKind::ConstEquate(_, _)
1336 | ty::PredicateKind::TypeWellFormedFromEnv(_)
1337 | ty::PredicateKind::Ambiguous => bug!(),
1341 // Expand trait aliases recursively and check that only one regular (non-auto) trait
1342 // is used and no 'maybe' bounds are used.
1343 let expanded_traits =
1344 traits::expand_trait_aliases(tcx, trait_bounds.iter().map(|&(a, b, _)| (a, b)));
1346 let (mut auto_traits, regular_traits): (Vec<_>, Vec<_>) = expanded_traits
1347 .filter(|i| i.trait_ref().self_ty().skip_binder() == dummy_self)
1348 .partition(|i| tcx.trait_is_auto(i.trait_ref().def_id()));
1349 if regular_traits.len() > 1 {
1350 let first_trait = ®ular_traits[0];
1351 let additional_trait = ®ular_traits[1];
1352 let mut err = struct_span_err!(
1354 additional_trait.bottom().1,
1356 "only auto traits can be used as additional traits in a trait object"
1358 additional_trait.label_with_exp_info(
1360 "additional non-auto trait",
1363 first_trait.label_with_exp_info(&mut err, "first non-auto trait", "first use");
1365 "consider creating a new trait with all of these as supertraits and using that \
1366 trait here instead: `trait NewTrait: {} {{}}`",
1369 .map(|t| t.trait_ref().print_only_trait_path().to_string())
1370 .collect::<Vec<_>>()
1374 "auto-traits like `Send` and `Sync` are traits that have special properties; \
1375 for more information on them, visit \
1376 <https://doc.rust-lang.org/reference/special-types-and-traits.html#auto-traits>",
1381 if regular_traits.is_empty() && auto_traits.is_empty() {
1382 let trait_alias_span = trait_bounds
1384 .map(|&(trait_ref, _, _)| trait_ref.def_id())
1385 .find(|&trait_ref| tcx.is_trait_alias(trait_ref))
1386 .map(|trait_ref| tcx.def_span(trait_ref));
1388 tcx.sess.emit_err(TraitObjectDeclaredWithNoTraits { span, trait_alias_span });
1389 return tcx.ty_error_with_guaranteed(reported);
1392 // Check that there are no gross object safety violations;
1393 // most importantly, that the supertraits don't contain `Self`,
1395 for item in ®ular_traits {
1396 let object_safety_violations =
1397 astconv_object_safety_violations(tcx, item.trait_ref().def_id());
1398 if !object_safety_violations.is_empty() {
1399 let reported = report_object_safety_error(
1402 item.trait_ref().def_id(),
1403 &object_safety_violations,
1406 return tcx.ty_error_with_guaranteed(reported);
1410 // Use a `BTreeSet` to keep output in a more consistent order.
1411 let mut associated_types: FxHashMap<Span, BTreeSet<DefId>> = FxHashMap::default();
1413 let regular_traits_refs_spans = trait_bounds
1415 .filter(|(trait_ref, _, _)| !tcx.trait_is_auto(trait_ref.def_id()));
1417 for (base_trait_ref, span, constness) in regular_traits_refs_spans {
1418 assert_eq!(constness, ty::BoundConstness::NotConst);
1420 for obligation in traits::elaborate_trait_ref(tcx, base_trait_ref) {
1422 "conv_object_ty_poly_trait_ref: observing object predicate `{:?}`",
1423 obligation.predicate
1426 let bound_predicate = obligation.predicate.kind();
1427 match bound_predicate.skip_binder() {
1428 ty::PredicateKind::Clause(ty::Clause::Trait(pred)) => {
1429 let pred = bound_predicate.rebind(pred);
1430 associated_types.entry(span).or_default().extend(
1431 tcx.associated_items(pred.def_id())
1432 .in_definition_order()
1433 .filter(|item| item.kind == ty::AssocKind::Type)
1434 .map(|item| item.def_id),
1437 ty::PredicateKind::Clause(ty::Clause::Projection(pred)) => {
1438 let pred = bound_predicate.rebind(pred);
1439 // A `Self` within the original bound will be substituted with a
1440 // `trait_object_dummy_self`, so check for that.
1441 let references_self = match pred.skip_binder().term.unpack() {
1442 ty::TermKind::Ty(ty) => ty.walk().any(|arg| arg == dummy_self.into()),
1443 ty::TermKind::Const(c) => {
1444 c.ty().walk().any(|arg| arg == dummy_self.into())
1448 // If the projection output contains `Self`, force the user to
1449 // elaborate it explicitly to avoid a lot of complexity.
1451 // The "classically useful" case is the following:
1453 // trait MyTrait: FnMut() -> <Self as MyTrait>::MyOutput {
1458 // Here, the user could theoretically write `dyn MyTrait<Output = X>`,
1459 // but actually supporting that would "expand" to an infinitely-long type
1460 // `fix $ τ → dyn MyTrait<MyOutput = X, Output = <τ as MyTrait>::MyOutput`.
1462 // Instead, we force the user to write
1463 // `dyn MyTrait<MyOutput = X, Output = X>`, which is uglier but works. See
1464 // the discussion in #56288 for alternatives.
1465 if !references_self {
1466 // Include projections defined on supertraits.
1467 projection_bounds.push((pred, span));
1475 for (projection_bound, _) in &projection_bounds {
1476 for def_ids in associated_types.values_mut() {
1477 def_ids.remove(&projection_bound.projection_def_id());
1481 self.complain_about_missing_associated_types(
1483 potential_assoc_types,
1487 // De-duplicate auto traits so that, e.g., `dyn Trait + Send + Send` is the same as
1488 // `dyn Trait + Send`.
1489 // We remove duplicates by inserting into a `FxHashSet` to avoid re-ordering
1491 let mut duplicates = FxHashSet::default();
1492 auto_traits.retain(|i| duplicates.insert(i.trait_ref().def_id()));
1493 debug!("regular_traits: {:?}", regular_traits);
1494 debug!("auto_traits: {:?}", auto_traits);
1496 // Erase the `dummy_self` (`trait_object_dummy_self`) used above.
1497 let existential_trait_refs = regular_traits.iter().map(|i| {
1498 i.trait_ref().map_bound(|trait_ref: ty::TraitRef<'tcx>| {
1499 assert_eq!(trait_ref.self_ty(), dummy_self);
1501 // Verify that `dummy_self` did not leak inside default type parameters. This
1502 // could not be done at path creation, since we need to see through trait aliases.
1503 let mut missing_type_params = vec![];
1504 let mut references_self = false;
1505 let generics = tcx.generics_of(trait_ref.def_id);
1506 let substs: Vec<_> = trait_ref
1510 .skip(1) // Remove `Self` for `ExistentialPredicate`.
1511 .map(|(index, arg)| {
1512 if arg == dummy_self.into() {
1513 let param = &generics.params[index];
1514 missing_type_params.push(param.name);
1515 return tcx.ty_error().into();
1516 } else if arg.walk().any(|arg| arg == dummy_self.into()) {
1517 references_self = true;
1518 return tcx.ty_error().into();
1523 let substs = tcx.intern_substs(&substs[..]);
1525 let span = i.bottom().1;
1526 let empty_generic_args = hir_trait_bounds.iter().any(|hir_bound| {
1527 hir_bound.trait_ref.path.res == Res::Def(DefKind::Trait, trait_ref.def_id)
1528 && hir_bound.span.contains(span)
1530 self.complain_about_missing_type_params(
1531 missing_type_params,
1537 if references_self {
1538 let def_id = i.bottom().0.def_id();
1539 let mut err = struct_span_err!(
1543 "the {} `{}` cannot be made into an object",
1544 tcx.def_kind(def_id).descr(def_id),
1545 tcx.item_name(def_id),
1548 rustc_middle::traits::ObjectSafetyViolation::SupertraitSelf(smallvec![])
1554 ty::ExistentialTraitRef { def_id: trait_ref.def_id, substs }
1558 let existential_projections = projection_bounds.iter().map(|(bound, _)| {
1559 bound.map_bound(|mut b| {
1560 assert_eq!(b.projection_ty.self_ty(), dummy_self);
1562 // Like for trait refs, verify that `dummy_self` did not leak inside default type
1564 let references_self = b.projection_ty.substs.iter().skip(1).any(|arg| {
1565 if arg.walk().any(|arg| arg == dummy_self.into()) {
1570 if references_self {
1572 .delay_span_bug(span, "trait object projection bounds reference `Self`");
1573 let substs: Vec<_> = b
1578 if arg.walk().any(|arg| arg == dummy_self.into()) {
1579 return tcx.ty_error().into();
1584 b.projection_ty.substs = tcx.intern_substs(&substs[..]);
1587 ty::ExistentialProjection::erase_self_ty(tcx, b)
1591 let regular_trait_predicates = existential_trait_refs
1592 .map(|trait_ref| trait_ref.map_bound(ty::ExistentialPredicate::Trait));
1593 let auto_trait_predicates = auto_traits.into_iter().map(|trait_ref| {
1594 ty::Binder::dummy(ty::ExistentialPredicate::AutoTrait(trait_ref.trait_ref().def_id()))
1596 // N.b. principal, projections, auto traits
1597 // FIXME: This is actually wrong with multiple principals in regards to symbol mangling
1598 let mut v = regular_trait_predicates
1600 existential_projections.map(|x| x.map_bound(ty::ExistentialPredicate::Projection)),
1602 .chain(auto_trait_predicates)
1603 .collect::<SmallVec<[_; 8]>>();
1604 v.sort_by(|a, b| a.skip_binder().stable_cmp(tcx, &b.skip_binder()));
1606 let existential_predicates = tcx.mk_poly_existential_predicates(v.into_iter());
1608 // Use explicitly-specified region bound.
1609 let region_bound = if !lifetime.is_elided() {
1610 self.ast_region_to_region(lifetime, None)
1612 self.compute_object_lifetime_bound(span, existential_predicates).unwrap_or_else(|| {
1613 if tcx.named_region(lifetime.hir_id).is_some() {
1614 self.ast_region_to_region(lifetime, None)
1616 self.re_infer(None, span).unwrap_or_else(|| {
1617 let mut err = struct_span_err!(
1621 "the lifetime bound for this object type cannot be deduced \
1622 from context; please supply an explicit bound"
1625 // We will have already emitted an error E0106 complaining about a
1626 // missing named lifetime in `&dyn Trait`, so we elide this one.
1631 tcx.lifetimes.re_static
1636 debug!("region_bound: {:?}", region_bound);
1638 let ty = tcx.mk_dynamic(existential_predicates, region_bound, representation);
1639 debug!("trait_object_type: {:?}", ty);
1643 fn report_ambiguous_associated_type(
1649 ) -> ErrorGuaranteed {
1650 let mut err = struct_span_err!(self.tcx().sess, span, E0223, "ambiguous associated type");
1654 .confused_type_with_std_module
1656 .any(|full_span| full_span.contains(span))
1658 err.span_suggestion(
1659 span.shrink_to_lo(),
1660 "you are looking for the module in `std`, not the primitive type",
1662 Applicability::MachineApplicable,
1665 err.span_suggestion(
1667 "use fully-qualified syntax",
1668 format!("<{} as {}>::{}", type_str, trait_str, name),
1669 Applicability::HasPlaceholders,
1675 // Search for a bound on a type parameter which includes the associated item
1676 // given by `assoc_name`. `ty_param_def_id` is the `DefId` of the type parameter
1677 // This function will fail if there are no suitable bounds or there is
1679 fn find_bound_for_assoc_item(
1681 ty_param_def_id: LocalDefId,
1684 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed> {
1685 let tcx = self.tcx();
1688 "find_bound_for_assoc_item(ty_param_def_id={:?}, assoc_name={:?}, span={:?})",
1689 ty_param_def_id, assoc_name, span,
1692 let predicates = &self
1693 .get_type_parameter_bounds(span, ty_param_def_id.to_def_id(), assoc_name)
1696 debug!("find_bound_for_assoc_item: predicates={:#?}", predicates);
1698 let param_name = tcx.hir().ty_param_name(ty_param_def_id);
1699 self.one_bound_for_assoc_type(
1701 traits::transitive_bounds_that_define_assoc_type(
1703 predicates.iter().filter_map(|(p, _)| {
1704 Some(p.to_opt_poly_trait_pred()?.map_bound(|t| t.trait_ref))
1709 || param_name.to_string(),
1716 // Checks that `bounds` contains exactly one element and reports appropriate
1717 // errors otherwise.
1718 #[instrument(level = "debug", skip(self, all_candidates, ty_param_name, is_equality), ret)]
1719 fn one_bound_for_assoc_type<I>(
1721 all_candidates: impl Fn() -> I,
1722 ty_param_name: impl Fn() -> String,
1725 is_equality: impl Fn() -> Option<String>,
1726 ) -> Result<ty::PolyTraitRef<'tcx>, ErrorGuaranteed>
1728 I: Iterator<Item = ty::PolyTraitRef<'tcx>>,
1730 let mut matching_candidates = all_candidates()
1731 .filter(|r| self.trait_defines_associated_type_named(r.def_id(), assoc_name));
1732 let mut const_candidates = all_candidates()
1733 .filter(|r| self.trait_defines_associated_const_named(r.def_id(), assoc_name));
1735 let (bound, next_cand) = match (matching_candidates.next(), const_candidates.next()) {
1736 (Some(bound), _) => (bound, matching_candidates.next()),
1737 (None, Some(bound)) => (bound, const_candidates.next()),
1739 let reported = self.complain_about_assoc_type_not_found(
1745 return Err(reported);
1750 if let Some(bound2) = next_cand {
1753 let is_equality = is_equality();
1754 let bounds = IntoIterator::into_iter([bound, bound2]).chain(matching_candidates);
1755 let mut err = if is_equality.is_some() {
1756 // More specific Error Index entry.
1761 "ambiguous associated type `{}` in bounds of `{}`",
1770 "ambiguous associated type `{}` in bounds of `{}`",
1775 err.span_label(span, format!("ambiguous associated type `{}`", assoc_name));
1777 let mut where_bounds = vec![];
1778 for bound in bounds {
1779 let bound_id = bound.def_id();
1780 let bound_span = self
1782 .associated_items(bound_id)
1783 .find_by_name_and_kind(self.tcx(), assoc_name, ty::AssocKind::Type, bound_id)
1784 .and_then(|item| self.tcx().hir().span_if_local(item.def_id));
1786 if let Some(bound_span) = bound_span {
1790 "ambiguous `{}` from `{}`",
1792 bound.print_only_trait_path(),
1795 if let Some(constraint) = &is_equality {
1796 where_bounds.push(format!(
1797 " T: {trait}::{assoc} = {constraint}",
1798 trait=bound.print_only_trait_path(),
1800 constraint=constraint,
1803 err.span_suggestion_verbose(
1804 span.with_hi(assoc_name.span.lo()),
1805 "use fully qualified syntax to disambiguate",
1809 bound.print_only_trait_path(),
1811 Applicability::MaybeIncorrect,
1816 "associated type `{}` could derive from `{}`",
1818 bound.print_only_trait_path(),
1822 if !where_bounds.is_empty() {
1824 "consider introducing a new type parameter `T` and adding `where` constraints:\
1825 \n where\n T: {},\n{}",
1827 where_bounds.join(",\n"),
1830 let reported = err.emit();
1831 if !where_bounds.is_empty() {
1832 return Err(reported);
1839 // Create a type from a path to an associated type or to an enum variant.
1840 // For a path `A::B::C::D`, `qself_ty` and `qself_def` are the type and def for `A::B::C`
1841 // and item_segment is the path segment for `D`. We return a type and a def for
1843 // Will fail except for `T::A` and `Self::A`; i.e., if `qself_ty`/`qself_def` are not a type
1844 // parameter or `Self`.
1845 // NOTE: When this function starts resolving `Trait::AssocTy` successfully
1846 // it should also start reporting the `BARE_TRAIT_OBJECTS` lint.
1847 #[instrument(level = "debug", skip(self, hir_ref_id, span, qself, assoc_segment), fields(assoc_ident=?assoc_segment.ident), ret)]
1848 pub fn associated_path_to_ty(
1850 hir_ref_id: hir::HirId,
1853 qself: &hir::Ty<'_>,
1854 assoc_segment: &hir::PathSegment<'_>,
1855 permit_variants: bool,
1856 ) -> Result<(Ty<'tcx>, DefKind, DefId), ErrorGuaranteed> {
1857 let tcx = self.tcx();
1858 let assoc_ident = assoc_segment.ident;
1859 let qself_res = if let hir::TyKind::Path(hir::QPath::Resolved(_, ref path)) = qself.kind {
1865 // Check if we have an enum variant.
1866 let mut variant_resolution = None;
1867 if let Some(adt_def) = self.probe_adt(span, qself_ty) {
1868 if adt_def.is_enum() {
1869 let variant_def = adt_def
1872 .find(|vd| tcx.hygienic_eq(assoc_ident, vd.ident(tcx), adt_def.did()));
1873 if let Some(variant_def) = variant_def {
1874 if permit_variants {
1875 tcx.check_stability(variant_def.def_id, Some(hir_ref_id), span, None);
1876 self.prohibit_generics(slice::from_ref(assoc_segment).iter(), |err| {
1877 err.note("enum variants can't have type parameters");
1878 let type_name = tcx.item_name(adt_def.did());
1880 "you might have meant to specity type parameters on enum \
1883 let Some(args) = assoc_segment.args else { return; };
1884 // Get the span of the generics args *including* the leading `::`.
1885 let args_span = assoc_segment.ident.span.shrink_to_hi().to(args.span_ext);
1886 if tcx.generics_of(adt_def.did()).count() == 0 {
1887 // FIXME(estebank): we could also verify that the arguments being
1888 // work for the `enum`, instead of just looking if it takes *any*.
1889 err.span_suggestion_verbose(
1891 &format!("{type_name} doesn't have generic parameters"),
1893 Applicability::MachineApplicable,
1897 let Ok(snippet) = tcx.sess.source_map().span_to_snippet(args_span) else {
1901 let (qself_sugg_span, is_self) = if let hir::TyKind::Path(
1902 hir::QPath::Resolved(_, ref path)
1904 // If the path segment already has type params, we want to overwrite
1906 match &path.segments[..] {
1907 // `segment` is the previous to last element on the path,
1908 // which would normally be the `enum` itself, while the last
1909 // `_` `PathSegment` corresponds to the variant.
1910 [.., hir::PathSegment {
1913 res: Res::Def(DefKind::Enum, _),
1916 // We need to include the `::` in `Type::Variant::<Args>`
1917 // to point the span to `::<Args>`, not just `<Args>`.
1918 ident.span.shrink_to_hi().to(args.map_or(
1919 ident.span.shrink_to_hi(),
1924 // We need to include the `::` in `Type::Variant::<Args>`
1925 // to point the span to `::<Args>`, not just `<Args>`.
1926 segment.ident.span.shrink_to_hi().to(segment.args.map_or(
1927 segment.ident.span.shrink_to_hi(),
1929 kw::SelfUpper == segment.ident.name,
1940 let suggestion = vec![
1942 // Account for people writing `Self::Variant::<Args>`, where
1943 // `Self` is the enum, and suggest replacing `Self` with the
1944 // appropriate type: `Type::<Args>::Variant`.
1945 (qself.span, format!("{type_name}{snippet}"))
1947 (qself_sugg_span, snippet)
1949 (args_span, String::new()),
1951 err.multipart_suggestion_verbose(
1954 Applicability::MaybeIncorrect,
1957 return Ok((qself_ty, DefKind::Variant, variant_def.def_id));
1959 variant_resolution = Some(variant_def.def_id);
1964 // see if we can satisfy using an inherent associated type
1965 for &impl_ in tcx.inherent_impls(adt_def.did()) {
1966 let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, impl_) else {
1969 let ty::Adt(_, adt_substs) = qself_ty.kind() else {
1970 // FIXME(inherent_associated_types)
1971 bug!("unimplemented: non-adt self of inherent assoc ty");
1973 let item_substs = self.create_substs_for_associated_item(
1979 let ty = tcx.bound_type_of(assoc_ty_did).subst(tcx, item_substs);
1980 return Ok((ty, DefKind::AssocTy, assoc_ty_did));
1984 // Find the type of the associated item, and the trait where the associated
1985 // item is declared.
1986 let bound = match (&qself_ty.kind(), qself_res) {
1987 (_, Res::SelfTyAlias { alias_to: impl_def_id, is_trait_impl: true, .. }) => {
1988 // `Self` in an impl of a trait -- we have a concrete self type and a
1990 let Some(trait_ref) = tcx.impl_trait_ref(impl_def_id) else {
1991 // A cycle error occurred, most likely.
1992 let guar = tcx.sess.delay_span_bug(span, "expected cycle error");
1996 self.one_bound_for_assoc_type(
1997 || traits::supertraits(tcx, ty::Binder::dummy(trait_ref)),
1998 || "Self".to_string(),
2006 Res::SelfTyParam { trait_: param_did } | Res::Def(DefKind::TyParam, param_did),
2007 ) => self.find_bound_for_assoc_item(param_did.expect_local(), assoc_ident, span)?,
2009 let reported = if variant_resolution.is_some() {
2010 // Variant in type position
2011 let msg = format!("expected type, found variant `{}`", assoc_ident);
2012 tcx.sess.span_err(span, &msg)
2013 } else if qself_ty.is_enum() {
2014 let mut err = struct_span_err!(
2018 "no variant named `{}` found for enum `{}`",
2023 let adt_def = qself_ty.ty_adt_def().expect("enum is not an ADT");
2024 if let Some(suggested_name) = find_best_match_for_name(
2028 .map(|variant| variant.name)
2029 .collect::<Vec<Symbol>>(),
2033 err.span_suggestion(
2035 "there is a variant with a similar name",
2037 Applicability::MaybeIncorrect,
2042 format!("variant not found in `{}`", qself_ty),
2046 if let Some(sp) = tcx.hir().span_if_local(adt_def.did()) {
2047 err.span_label(sp, format!("variant `{}` not found here", assoc_ident));
2051 } else if let Err(reported) = qself_ty.error_reported() {
2054 // Don't print `TyErr` to the user.
2055 self.report_ambiguous_associated_type(
2057 &qself_ty.to_string(),
2062 return Err(reported);
2066 let trait_did = bound.def_id();
2067 let Some(assoc_ty_did) = self.lookup_assoc_ty(assoc_ident, hir_ref_id, span, trait_did) else {
2068 // Assume that if it's not matched, there must be a const defined with the same name
2069 // but it was used in a type position.
2070 let msg = format!("found associated const `{assoc_ident}` when type was expected");
2071 let guar = tcx.sess.struct_span_err(span, &msg).emit();
2075 let ty = self.projected_ty_from_poly_trait_ref(span, assoc_ty_did, assoc_segment, bound);
2077 if let Some(variant_def_id) = variant_resolution {
2078 tcx.struct_span_lint_hir(
2079 AMBIGUOUS_ASSOCIATED_ITEMS,
2082 "ambiguous associated item",
2084 let mut could_refer_to = |kind: DefKind, def_id, also| {
2085 let note_msg = format!(
2086 "`{}` could{} refer to the {} defined here",
2091 lint.span_note(tcx.def_span(def_id), ¬e_msg);
2094 could_refer_to(DefKind::Variant, variant_def_id, "");
2095 could_refer_to(DefKind::AssocTy, assoc_ty_did, " also");
2097 lint.span_suggestion(
2099 "use fully-qualified syntax",
2100 format!("<{} as {}>::{}", qself_ty, tcx.item_name(trait_did), assoc_ident),
2101 Applicability::MachineApplicable,
2108 Ok((ty, DefKind::AssocTy, assoc_ty_did))
2117 ) -> Option<DefId> {
2118 let tcx = self.tcx();
2119 let (ident, def_scope) = tcx.adjust_ident_and_get_scope(ident, scope, block);
2121 // We have already adjusted the item name above, so compare with `ident.normalize_to_macros_2_0()` instead
2122 // of calling `find_by_name_and_kind`.
2123 let item = tcx.associated_items(scope).in_definition_order().find(|i| {
2124 i.kind.namespace() == Namespace::TypeNS
2125 && i.ident(tcx).normalize_to_macros_2_0() == ident
2128 let kind = DefKind::AssocTy;
2129 if !item.visibility(tcx).is_accessible_from(def_scope, tcx) {
2130 let kind = kind.descr(item.def_id);
2131 let msg = format!("{kind} `{ident}` is private");
2132 let def_span = self.tcx().def_span(item.def_id);
2134 .struct_span_err_with_code(span, &msg, rustc_errors::error_code!(E0624))
2135 .span_label(span, &format!("private {kind}"))
2136 .span_label(def_span, &format!("{kind} defined here"))
2139 tcx.check_stability(item.def_id, Some(block), span, None);
2147 opt_self_ty: Option<Ty<'tcx>>,
2149 trait_segment: &hir::PathSegment<'_>,
2150 item_segment: &hir::PathSegment<'_>,
2151 constness: ty::BoundConstness,
2153 let tcx = self.tcx();
2155 let trait_def_id = tcx.parent(item_def_id);
2157 debug!("qpath_to_ty: trait_def_id={:?}", trait_def_id);
2159 let Some(self_ty) = opt_self_ty else {
2160 let path_str = tcx.def_path_str(trait_def_id);
2162 let def_id = self.item_def_id();
2164 debug!("qpath_to_ty: self.item_def_id()={:?}", def_id);
2166 let parent_def_id = def_id.as_local().map(|def_id| tcx.hir().local_def_id_to_hir_id(def_id))
2167 .map(|hir_id| tcx.hir().get_parent_item(hir_id).to_def_id());
2169 debug!("qpath_to_ty: parent_def_id={:?}", parent_def_id);
2171 // If the trait in segment is the same as the trait defining the item,
2172 // use the `<Self as ..>` syntax in the error.
2173 let is_part_of_self_trait_constraints = def_id == trait_def_id;
2174 let is_part_of_fn_in_self_trait = parent_def_id == Some(trait_def_id);
2176 let type_name = if is_part_of_self_trait_constraints || is_part_of_fn_in_self_trait {
2182 let reported = self.report_ambiguous_associated_type(
2186 item_segment.ident.name,
2188 return tcx.ty_error_with_guaranteed(reported)
2191 debug!("qpath_to_ty: self_type={:?}", self_ty);
2193 let trait_ref = self.ast_path_to_mono_trait_ref(
2202 let item_substs = self.create_substs_for_associated_item(
2209 debug!("qpath_to_ty: trait_ref={:?}", trait_ref);
2211 tcx.mk_projection(item_def_id, item_substs)
2214 pub fn prohibit_generics<'a>(
2216 segments: impl Iterator<Item = &'a hir::PathSegment<'a>> + Clone,
2217 extend: impl Fn(&mut Diagnostic),
2219 let args = segments.clone().flat_map(|segment| segment.args().args);
2221 let (lt, ty, ct, inf) =
2222 args.clone().fold((false, false, false, false), |(lt, ty, ct, inf), arg| match arg {
2223 hir::GenericArg::Lifetime(_) => (true, ty, ct, inf),
2224 hir::GenericArg::Type(_) => (lt, true, ct, inf),
2225 hir::GenericArg::Const(_) => (lt, ty, true, inf),
2226 hir::GenericArg::Infer(_) => (lt, ty, ct, true),
2228 let mut emitted = false;
2229 if lt || ty || ct || inf {
2230 let types_and_spans: Vec<_> = segments
2232 .flat_map(|segment| {
2233 if segment.args().args.is_empty() {
2238 Res::PrimTy(ty) => format!("{} `{}`", segment.res.descr(), ty.name()),
2240 if let Some(name) = self.tcx().opt_item_name(def_id) => {
2241 format!("{} `{name}`", segment.res.descr())
2243 Res::Err => "this type".to_string(),
2244 _ => segment.res.descr().to_string(),
2251 let this_type = match &types_and_spans[..] {
2252 [.., _, (last, _)] => format!(
2254 types_and_spans[..types_and_spans.len() - 1]
2256 .map(|(x, _)| x.as_str())
2258 .collect::<String>()
2260 [(only, _)] => only.to_string(),
2261 [] => "this type".to_string(),
2264 let arg_spans: Vec<Span> = args.map(|arg| arg.span()).collect();
2266 let mut kinds = Vec::with_capacity(4);
2268 kinds.push("lifetime");
2274 kinds.push("const");
2277 kinds.push("generic");
2279 let (kind, s) = match kinds[..] {
2283 kinds[..kinds.len() - 1]
2287 .collect::<String>()
2291 [only] => (only.to_string(), ""),
2292 [] => unreachable!(),
2294 let last_span = *arg_spans.last().unwrap();
2295 let span: MultiSpan = arg_spans.into();
2296 let mut err = struct_span_err!(
2300 "{kind} arguments are not allowed on {this_type}",
2302 err.span_label(last_span, format!("{kind} argument{s} not allowed"));
2303 for (what, span) in types_and_spans {
2304 err.span_label(span, format!("not allowed on {what}"));
2311 for segment in segments {
2312 // Only emit the first error to avoid overloading the user with error messages.
2313 if let Some(b) = segment.args().bindings.first() {
2314 prohibit_assoc_ty_binding(self.tcx(), b.span);
2321 // FIXME(eddyb, varkor) handle type paths here too, not just value ones.
2322 pub fn def_ids_for_value_path_segments(
2324 segments: &[hir::PathSegment<'_>],
2325 self_ty: Option<Ty<'tcx>>,
2330 // We need to extract the type parameters supplied by the user in
2331 // the path `path`. Due to the current setup, this is a bit of a
2332 // tricky-process; the problem is that resolve only tells us the
2333 // end-point of the path resolution, and not the intermediate steps.
2334 // Luckily, we can (at least for now) deduce the intermediate steps
2335 // just from the end-point.
2337 // There are basically five cases to consider:
2339 // 1. Reference to a constructor of a struct:
2341 // struct Foo<T>(...)
2343 // In this case, the parameters are declared in the type space.
2345 // 2. Reference to a constructor of an enum variant:
2347 // enum E<T> { Foo(...) }
2349 // In this case, the parameters are defined in the type space,
2350 // but may be specified either on the type or the variant.
2352 // 3. Reference to a fn item or a free constant:
2356 // In this case, the path will again always have the form
2357 // `a::b::foo::<T>` where only the final segment should have
2358 // type parameters. However, in this case, those parameters are
2359 // declared on a value, and hence are in the `FnSpace`.
2361 // 4. Reference to a method or an associated constant:
2363 // impl<A> SomeStruct<A> {
2367 // Here we can have a path like
2368 // `a::b::SomeStruct::<A>::foo::<B>`, in which case parameters
2369 // may appear in two places. The penultimate segment,
2370 // `SomeStruct::<A>`, contains parameters in TypeSpace, and the
2371 // final segment, `foo::<B>` contains parameters in fn space.
2373 // The first step then is to categorize the segments appropriately.
2375 let tcx = self.tcx();
2377 assert!(!segments.is_empty());
2378 let last = segments.len() - 1;
2380 let mut path_segs = vec![];
2383 // Case 1. Reference to a struct constructor.
2384 DefKind::Ctor(CtorOf::Struct, ..) => {
2385 // Everything but the final segment should have no
2386 // parameters at all.
2387 let generics = tcx.generics_of(def_id);
2388 // Variant and struct constructors use the
2389 // generics of their parent type definition.
2390 let generics_def_id = generics.parent.unwrap_or(def_id);
2391 path_segs.push(PathSeg(generics_def_id, last));
2394 // Case 2. Reference to a variant constructor.
2395 DefKind::Ctor(CtorOf::Variant, ..) | DefKind::Variant => {
2396 let (generics_def_id, index) = if let Some(self_ty) = self_ty {
2397 let adt_def = self.probe_adt(span, self_ty).unwrap();
2398 debug_assert!(adt_def.is_enum());
2399 (adt_def.did(), last)
2400 } else if last >= 1 && segments[last - 1].args.is_some() {
2401 // Everything but the penultimate segment should have no
2402 // parameters at all.
2403 let mut def_id = def_id;
2405 // `DefKind::Ctor` -> `DefKind::Variant`
2406 if let DefKind::Ctor(..) = kind {
2407 def_id = tcx.parent(def_id);
2410 // `DefKind::Variant` -> `DefKind::Enum`
2411 let enum_def_id = tcx.parent(def_id);
2412 (enum_def_id, last - 1)
2414 // FIXME: lint here recommending `Enum::<...>::Variant` form
2415 // instead of `Enum::Variant::<...>` form.
2417 // Everything but the final segment should have no
2418 // parameters at all.
2419 let generics = tcx.generics_of(def_id);
2420 // Variant and struct constructors use the
2421 // generics of their parent type definition.
2422 (generics.parent.unwrap_or(def_id), last)
2424 path_segs.push(PathSeg(generics_def_id, index));
2427 // Case 3. Reference to a top-level value.
2428 DefKind::Fn | DefKind::Const | DefKind::ConstParam | DefKind::Static(_) => {
2429 path_segs.push(PathSeg(def_id, last));
2432 // Case 4. Reference to a method or associated const.
2433 DefKind::AssocFn | DefKind::AssocConst => {
2434 if segments.len() >= 2 {
2435 let generics = tcx.generics_of(def_id);
2436 path_segs.push(PathSeg(generics.parent.unwrap(), last - 1));
2438 path_segs.push(PathSeg(def_id, last));
2441 kind => bug!("unexpected definition kind {:?} for {:?}", kind, def_id),
2444 debug!("path_segs = {:?}", path_segs);
2449 /// Check a type `Path` and convert it to a `Ty`.
2452 opt_self_ty: Option<Ty<'tcx>>,
2453 path: &hir::Path<'_>,
2454 permit_variants: bool,
2456 let tcx = self.tcx();
2459 "res_to_ty(res={:?}, opt_self_ty={:?}, path_segments={:?})",
2460 path.res, opt_self_ty, path.segments
2463 let span = path.span;
2465 Res::Def(DefKind::OpaqueTy | DefKind::ImplTraitPlaceholder, did) => {
2466 // Check for desugared `impl Trait`.
2467 assert!(ty::is_impl_trait_defn(tcx, did).is_none());
2468 let item_segment = path.segments.split_last().unwrap();
2469 self.prohibit_generics(item_segment.1.iter(), |err| {
2470 err.note("`impl Trait` types can't have type parameters");
2472 let substs = self.ast_path_substs_for_ty(span, did, item_segment.0);
2473 tcx.mk_opaque(did, substs)
2480 | DefKind::ForeignTy,
2483 assert_eq!(opt_self_ty, None);
2484 self.prohibit_generics(path.segments.split_last().unwrap().1.iter(), |_| {});
2485 self.ast_path_to_ty(span, did, path.segments.last().unwrap())
2487 Res::Def(kind @ DefKind::Variant, def_id) if permit_variants => {
2488 // Convert "variant type" as if it were a real type.
2489 // The resulting `Ty` is type of the variant's enum for now.
2490 assert_eq!(opt_self_ty, None);
2493 self.def_ids_for_value_path_segments(path.segments, None, kind, def_id, span);
2494 let generic_segs: FxHashSet<_> =
2495 path_segs.iter().map(|PathSeg(_, index)| index).collect();
2496 self.prohibit_generics(
2497 path.segments.iter().enumerate().filter_map(|(index, seg)| {
2498 if !generic_segs.contains(&index) { Some(seg) } else { None }
2501 err.note("enum variants can't have type parameters");
2505 let PathSeg(def_id, index) = path_segs.last().unwrap();
2506 self.ast_path_to_ty(span, *def_id, &path.segments[*index])
2508 Res::Def(DefKind::TyParam, def_id) => {
2509 assert_eq!(opt_self_ty, None);
2510 self.prohibit_generics(path.segments.iter(), |err| {
2511 if let Some(span) = tcx.def_ident_span(def_id) {
2512 let name = tcx.item_name(def_id);
2513 err.span_note(span, &format!("type parameter `{name}` defined here"));
2517 let def_id = def_id.expect_local();
2518 let item_def_id = tcx.hir().ty_param_owner(def_id);
2519 let generics = tcx.generics_of(item_def_id);
2520 let index = generics.param_def_id_to_index[&def_id.to_def_id()];
2521 tcx.mk_ty_param(index, tcx.hir().ty_param_name(def_id))
2523 Res::SelfTyParam { .. } => {
2524 // `Self` in trait or type alias.
2525 assert_eq!(opt_self_ty, None);
2526 self.prohibit_generics(path.segments.iter(), |err| {
2527 if let [hir::PathSegment { args: Some(args), ident, .. }] = &path.segments[..] {
2528 err.span_suggestion_verbose(
2529 ident.span.shrink_to_hi().to(args.span_ext),
2530 "the `Self` type doesn't accept type parameters",
2532 Applicability::MaybeIncorrect,
2536 tcx.types.self_param
2538 Res::SelfTyAlias { alias_to: def_id, forbid_generic, .. } => {
2539 // `Self` in impl (we know the concrete type).
2540 assert_eq!(opt_self_ty, None);
2541 // Try to evaluate any array length constants.
2542 let ty = tcx.at(span).type_of(def_id);
2543 let span_of_impl = tcx.span_of_impl(def_id);
2544 self.prohibit_generics(path.segments.iter(), |err| {
2545 let def_id = match *ty.kind() {
2546 ty::Adt(self_def, _) => self_def.did(),
2550 let type_name = tcx.item_name(def_id);
2551 let span_of_ty = tcx.def_ident_span(def_id);
2552 let generics = tcx.generics_of(def_id).count();
2554 let msg = format!("`Self` is of type `{ty}`");
2555 if let (Ok(i_sp), Some(t_sp)) = (span_of_impl, span_of_ty) {
2556 let mut span: MultiSpan = vec![t_sp].into();
2557 span.push_span_label(
2559 &format!("`Self` is on type `{type_name}` in this `impl`"),
2561 let mut postfix = "";
2563 postfix = ", which doesn't have generic parameters";
2565 span.push_span_label(
2567 &format!("`Self` corresponds to this type{postfix}"),
2569 err.span_note(span, &msg);
2573 for segment in path.segments {
2574 if let Some(args) = segment.args && segment.ident.name == kw::SelfUpper {
2576 // FIXME(estebank): we could also verify that the arguments being
2577 // work for the `enum`, instead of just looking if it takes *any*.
2578 err.span_suggestion_verbose(
2579 segment.ident.span.shrink_to_hi().to(args.span_ext),
2580 "the `Self` type doesn't accept type parameters",
2582 Applicability::MachineApplicable,
2586 err.span_suggestion_verbose(
2589 "the `Self` type doesn't accept type parameters, use the \
2590 concrete type's name `{type_name}` instead if you want to \
2591 specify its type parameters"
2594 Applicability::MaybeIncorrect,
2600 // HACK(min_const_generics): Forbid generic `Self` types
2601 // here as we can't easily do that during nameres.
2603 // We do this before normalization as we otherwise allow
2605 // trait AlwaysApplicable { type Assoc; }
2606 // impl<T: ?Sized> AlwaysApplicable for T { type Assoc = usize; }
2608 // trait BindsParam<T> {
2611 // impl<T> BindsParam<T> for <T as AlwaysApplicable>::Assoc {
2612 // type ArrayTy = [u8; Self::MAX];
2615 // Note that the normalization happens in the param env of
2616 // the anon const, which is empty. This is why the
2617 // `AlwaysApplicable` impl needs a `T: ?Sized` bound for
2618 // this to compile if we were to normalize here.
2619 if forbid_generic && ty.needs_subst() {
2620 let mut err = tcx.sess.struct_span_err(
2622 "generic `Self` types are currently not permitted in anonymous constants",
2624 if let Some(hir::Node::Item(&hir::Item {
2625 kind: hir::ItemKind::Impl(ref impl_),
2627 })) = tcx.hir().get_if_local(def_id)
2629 err.span_note(impl_.self_ty.span, "not a concrete type");
2631 tcx.ty_error_with_guaranteed(err.emit())
2636 Res::Def(DefKind::AssocTy, def_id) => {
2637 debug_assert!(path.segments.len() >= 2);
2638 self.prohibit_generics(path.segments[..path.segments.len() - 2].iter(), |_| {});
2639 // HACK: until we support `<Type as ~const Trait>`, assume all of them are.
2640 let constness = if tcx.has_attr(tcx.parent(def_id), sym::const_trait) {
2641 ty::BoundConstness::ConstIfConst
2643 ty::BoundConstness::NotConst
2649 &path.segments[path.segments.len() - 2],
2650 path.segments.last().unwrap(),
2654 Res::PrimTy(prim_ty) => {
2655 assert_eq!(opt_self_ty, None);
2656 self.prohibit_generics(path.segments.iter(), |err| {
2657 let name = prim_ty.name_str();
2658 for segment in path.segments {
2659 if let Some(args) = segment.args {
2660 err.span_suggestion_verbose(
2661 segment.ident.span.shrink_to_hi().to(args.span_ext),
2662 &format!("primitive type `{name}` doesn't have generic parameters"),
2664 Applicability::MaybeIncorrect,
2670 hir::PrimTy::Bool => tcx.types.bool,
2671 hir::PrimTy::Char => tcx.types.char,
2672 hir::PrimTy::Int(it) => tcx.mk_mach_int(ty::int_ty(it)),
2673 hir::PrimTy::Uint(uit) => tcx.mk_mach_uint(ty::uint_ty(uit)),
2674 hir::PrimTy::Float(ft) => tcx.mk_mach_float(ty::float_ty(ft)),
2675 hir::PrimTy::Str => tcx.types.str_,
2682 .delay_span_bug(path.span, "path with `Res::Err` but no error emitted");
2683 self.set_tainted_by_errors(e);
2684 self.tcx().ty_error_with_guaranteed(e)
2686 _ => span_bug!(span, "unexpected resolution: {:?}", path.res),
2690 /// Parses the programmer's textual representation of a type into our
2691 /// internal notion of a type.
2692 pub fn ast_ty_to_ty(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2693 self.ast_ty_to_ty_inner(ast_ty, false, false)
2696 /// Parses the programmer's textual representation of a type into our
2697 /// internal notion of a type. This is meant to be used within a path.
2698 pub fn ast_ty_to_ty_in_path(&self, ast_ty: &hir::Ty<'_>) -> Ty<'tcx> {
2699 self.ast_ty_to_ty_inner(ast_ty, false, true)
2702 /// Turns a `hir::Ty` into a `Ty`. For diagnostics' purposes we keep track of whether trait
2703 /// objects are borrowed like `&dyn Trait` to avoid emitting redundant errors.
2704 #[instrument(level = "debug", skip(self), ret)]
2705 fn ast_ty_to_ty_inner(&self, ast_ty: &hir::Ty<'_>, borrowed: bool, in_path: bool) -> Ty<'tcx> {
2706 let tcx = self.tcx();
2708 let result_ty = match ast_ty.kind {
2709 hir::TyKind::Slice(ref ty) => tcx.mk_slice(self.ast_ty_to_ty(ty)),
2710 hir::TyKind::Ptr(ref mt) => {
2711 tcx.mk_ptr(ty::TypeAndMut { ty: self.ast_ty_to_ty(mt.ty), mutbl: mt.mutbl })
2713 hir::TyKind::Ref(ref region, ref mt) => {
2714 let r = self.ast_region_to_region(region, None);
2716 let t = self.ast_ty_to_ty_inner(mt.ty, true, false);
2717 tcx.mk_ref(r, ty::TypeAndMut { ty: t, mutbl: mt.mutbl })
2719 hir::TyKind::Never => tcx.types.never,
2720 hir::TyKind::Tup(fields) => tcx.mk_tup(fields.iter().map(|t| self.ast_ty_to_ty(t))),
2721 hir::TyKind::BareFn(bf) => {
2722 require_c_abi_if_c_variadic(tcx, bf.decl, bf.abi, ast_ty.span);
2724 tcx.mk_fn_ptr(self.ty_of_fn(
2733 hir::TyKind::TraitObject(bounds, ref lifetime, repr) => {
2734 self.maybe_lint_bare_trait(ast_ty, in_path);
2735 let repr = match repr {
2736 TraitObjectSyntax::Dyn | TraitObjectSyntax::None => ty::Dyn,
2737 TraitObjectSyntax::DynStar => ty::DynStar,
2739 self.conv_object_ty_poly_trait_ref(ast_ty.span, bounds, lifetime, borrowed, repr)
2741 hir::TyKind::Path(hir::QPath::Resolved(ref maybe_qself, ref path)) => {
2742 debug!(?maybe_qself, ?path);
2743 let opt_self_ty = maybe_qself.as_ref().map(|qself| self.ast_ty_to_ty(qself));
2744 self.res_to_ty(opt_self_ty, path, false)
2746 hir::TyKind::OpaqueDef(item_id, lifetimes, in_trait) => {
2747 let opaque_ty = tcx.hir().item(item_id);
2748 let def_id = item_id.owner_id.to_def_id();
2750 match opaque_ty.kind {
2751 hir::ItemKind::OpaqueTy(hir::OpaqueTy { origin, .. }) => {
2752 self.impl_trait_ty_to_ty(def_id, lifetimes, origin, in_trait)
2754 ref i => bug!("`impl Trait` pointed to non-opaque type?? {:#?}", i),
2757 hir::TyKind::Path(hir::QPath::TypeRelative(ref qself, ref segment)) => {
2758 debug!(?qself, ?segment);
2759 let ty = self.ast_ty_to_ty_inner(qself, false, true);
2760 self.associated_path_to_ty(ast_ty.hir_id, ast_ty.span, ty, qself, segment, false)
2761 .map(|(ty, _, _)| ty)
2762 .unwrap_or_else(|_| tcx.ty_error())
2764 hir::TyKind::Path(hir::QPath::LangItem(lang_item, span, _)) => {
2765 let def_id = tcx.require_lang_item(lang_item, Some(span));
2766 let (substs, _) = self.create_substs_for_ast_path(
2770 &hir::PathSegment::invalid(),
2771 &GenericArgs::none(),
2774 ty::BoundConstness::NotConst,
2776 EarlyBinder(tcx.at(span).type_of(def_id)).subst(tcx, substs)
2778 hir::TyKind::Array(ref ty, ref length) => {
2779 let length = match length {
2780 &hir::ArrayLen::Infer(_, span) => self.ct_infer(tcx.types.usize, None, span),
2781 hir::ArrayLen::Body(constant) => {
2782 ty::Const::from_anon_const(tcx, constant.def_id)
2786 tcx.mk_ty(ty::Array(self.ast_ty_to_ty(ty), length))
2788 hir::TyKind::Typeof(ref e) => {
2789 let ty_erased = tcx.type_of(e.def_id);
2790 let ty = tcx.fold_regions(ty_erased, |r, _| {
2791 if r.is_erased() { tcx.lifetimes.re_static } else { r }
2793 let span = ast_ty.span;
2794 tcx.sess.emit_err(TypeofReservedKeywordUsed {
2797 opt_sugg: Some((span, Applicability::MachineApplicable))
2798 .filter(|_| ty.is_suggestable(tcx, false)),
2803 hir::TyKind::Infer => {
2804 // Infer also appears as the type of arguments or return
2805 // values in an ExprKind::Closure, or as
2806 // the type of local variables. Both of these cases are
2807 // handled specially and will not descend into this routine.
2808 self.ty_infer(None, ast_ty.span)
2810 hir::TyKind::Err => tcx.ty_error(),
2813 self.record_ty(ast_ty.hir_id, result_ty, ast_ty.span);
2817 #[instrument(level = "debug", skip(self), ret)]
2818 fn impl_trait_ty_to_ty(
2821 lifetimes: &[hir::GenericArg<'_>],
2822 origin: OpaqueTyOrigin,
2825 debug!("impl_trait_ty_to_ty(def_id={:?}, lifetimes={:?})", def_id, lifetimes);
2826 let tcx = self.tcx();
2828 let generics = tcx.generics_of(def_id);
2830 debug!("impl_trait_ty_to_ty: generics={:?}", generics);
2831 let substs = InternalSubsts::for_item(tcx, def_id, |param, _| {
2832 if let Some(i) = (param.index as usize).checked_sub(generics.parent_count) {
2833 // Our own parameters are the resolved lifetimes.
2834 let GenericParamDefKind::Lifetime { .. } = param.kind else { bug!() };
2835 let hir::GenericArg::Lifetime(lifetime) = &lifetimes[i] else { bug!() };
2836 self.ast_region_to_region(lifetime, None).into()
2838 tcx.mk_param_from_def(param)
2841 debug!("impl_trait_ty_to_ty: substs={:?}", substs);
2843 if in_trait { tcx.mk_projection(def_id, substs) } else { tcx.mk_opaque(def_id, substs) }
2846 pub fn ty_of_arg(&self, ty: &hir::Ty<'_>, expected_ty: Option<Ty<'tcx>>) -> Ty<'tcx> {
2848 hir::TyKind::Infer if expected_ty.is_some() => {
2849 self.record_ty(ty.hir_id, expected_ty.unwrap(), ty.span);
2850 expected_ty.unwrap()
2852 _ => self.ast_ty_to_ty(ty),
2856 #[instrument(level = "debug", skip(self, hir_id, unsafety, abi, decl, generics, hir_ty), ret)]
2860 unsafety: hir::Unsafety,
2862 decl: &hir::FnDecl<'_>,
2863 generics: Option<&hir::Generics<'_>>,
2864 hir_ty: Option<&hir::Ty<'_>>,
2865 ) -> ty::PolyFnSig<'tcx> {
2866 let tcx = self.tcx();
2867 let bound_vars = tcx.late_bound_vars(hir_id);
2868 debug!(?bound_vars);
2870 // We proactively collect all the inferred type params to emit a single error per fn def.
2871 let mut visitor = HirPlaceholderCollector::default();
2872 let mut infer_replacements = vec![];
2874 if let Some(generics) = generics {
2875 walk_generics(&mut visitor, generics);
2878 let input_tys: Vec<_> = decl
2883 if let hir::TyKind::Infer = a.kind && !self.allow_ty_infer() {
2884 if let Some(suggested_ty) =
2885 self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, Some(i))
2887 infer_replacements.push((a.span, suggested_ty.to_string()));
2888 return suggested_ty;
2892 // Only visit the type looking for `_` if we didn't fix the type above
2893 visitor.visit_ty(a);
2894 self.ty_of_arg(a, None)
2898 let output_ty = match decl.output {
2899 hir::FnRetTy::Return(output) => {
2900 if let hir::TyKind::Infer = output.kind
2901 && !self.allow_ty_infer()
2902 && let Some(suggested_ty) =
2903 self.suggest_trait_fn_ty_for_impl_fn_infer(hir_id, None)
2905 infer_replacements.push((output.span, suggested_ty.to_string()));
2908 visitor.visit_ty(output);
2909 self.ast_ty_to_ty(output)
2912 hir::FnRetTy::DefaultReturn(..) => tcx.mk_unit(),
2917 let fn_ty = tcx.mk_fn_sig(input_tys.into_iter(), output_ty, decl.c_variadic, unsafety, abi);
2918 let bare_fn_ty = ty::Binder::bind_with_vars(fn_ty, bound_vars);
2920 if !self.allow_ty_infer() && !(visitor.0.is_empty() && infer_replacements.is_empty()) {
2921 // We always collect the spans for placeholder types when evaluating `fn`s, but we
2922 // only want to emit an error complaining about them if infer types (`_`) are not
2923 // allowed. `allow_ty_infer` gates this behavior. We check for the presence of
2924 // `ident_span` to not emit an error twice when we have `fn foo(_: fn() -> _)`.
2926 let mut diag = crate::collect::placeholder_type_error_diag(
2930 infer_replacements.iter().map(|(s, _)| *s).collect(),
2936 if !infer_replacements.is_empty() {
2937 diag.multipart_suggestion(
2939 "try replacing `_` with the type{} in the corresponding trait method signature",
2940 rustc_errors::pluralize!(infer_replacements.len()),
2943 Applicability::MachineApplicable,
2950 // Find any late-bound regions declared in return type that do
2951 // not appear in the arguments. These are not well-formed.
2954 // for<'a> fn() -> &'a str <-- 'a is bad
2955 // for<'a> fn(&'a String) -> &'a str <-- 'a is ok
2956 let inputs = bare_fn_ty.inputs();
2957 let late_bound_in_args =
2958 tcx.collect_constrained_late_bound_regions(&inputs.map_bound(|i| i.to_owned()));
2959 let output = bare_fn_ty.output();
2960 let late_bound_in_ret = tcx.collect_referenced_late_bound_regions(&output);
2962 self.validate_late_bound_regions(late_bound_in_args, late_bound_in_ret, |br_name| {
2967 "return type references {}, which is not constrained by the fn input types",
2975 /// Given a fn_hir_id for a impl function, suggest the type that is found on the
2976 /// corresponding function in the trait that the impl implements, if it exists.
2977 /// If arg_idx is Some, then it corresponds to an input type index, otherwise it
2978 /// corresponds to the return type.
2979 fn suggest_trait_fn_ty_for_impl_fn_infer(
2981 fn_hir_id: hir::HirId,
2982 arg_idx: Option<usize>,
2983 ) -> Option<Ty<'tcx>> {
2984 let tcx = self.tcx();
2985 let hir = tcx.hir();
2987 let hir::Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Fn(..), ident, .. }) =
2988 hir.get(fn_hir_id) else { return None };
2989 let hir::Node::Item(hir::Item { kind: hir::ItemKind::Impl(i), .. }) =
2990 hir.get_parent(fn_hir_id) else { bug!("ImplItem should have Impl parent") };
2992 let trait_ref = self.instantiate_mono_trait_ref(
2993 i.of_trait.as_ref()?,
2994 self.ast_ty_to_ty(i.self_ty),
2995 ty::BoundConstness::NotConst,
2998 let assoc = tcx.associated_items(trait_ref.def_id).find_by_name_and_kind(
3005 let fn_sig = tcx.bound_fn_sig(assoc.def_id).subst(
3007 trait_ref.substs.extend_to(tcx, assoc.def_id, |param, _| tcx.mk_param_from_def(param)),
3010 let ty = if let Some(arg_idx) = arg_idx { fn_sig.input(arg_idx) } else { fn_sig.output() };
3012 Some(tcx.liberate_late_bound_regions(fn_hir_id.expect_owner().to_def_id(), ty))
3015 #[instrument(level = "trace", skip(self, generate_err))]
3016 fn validate_late_bound_regions(
3018 constrained_regions: FxHashSet<ty::BoundRegionKind>,
3019 referenced_regions: FxHashSet<ty::BoundRegionKind>,
3020 generate_err: impl Fn(&str) -> DiagnosticBuilder<'tcx, ErrorGuaranteed>,
3022 for br in referenced_regions.difference(&constrained_regions) {
3023 let br_name = match *br {
3024 ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) | ty::BrEnv => {
3025 "an anonymous lifetime".to_string()
3027 ty::BrNamed(_, name) => format!("lifetime `{}`", name),
3030 let mut err = generate_err(&br_name);
3032 if let ty::BrNamed(_, kw::UnderscoreLifetime) | ty::BrAnon(..) = *br {
3033 // The only way for an anonymous lifetime to wind up
3034 // in the return type but **also** be unconstrained is
3035 // if it only appears in "associated types" in the
3036 // input. See #47511 and #62200 for examples. In this case,
3037 // though we can easily give a hint that ought to be
3040 "lifetimes appearing in an associated or opaque type are not considered constrained",
3042 err.note("consider introducing a named lifetime parameter");
3049 /// Given the bounds on an object, determines what single region bound (if any) we can
3050 /// use to summarize this type. The basic idea is that we will use the bound the user
3051 /// provided, if they provided one, and otherwise search the supertypes of trait bounds
3052 /// for region bounds. It may be that we can derive no bound at all, in which case
3053 /// we return `None`.
3054 fn compute_object_lifetime_bound(
3057 existential_predicates: &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>>,
3058 ) -> Option<ty::Region<'tcx>> // if None, use the default
3060 let tcx = self.tcx();
3062 debug!("compute_opt_region_bound(existential_predicates={:?})", existential_predicates);
3064 // No explicit region bound specified. Therefore, examine trait
3065 // bounds and see if we can derive region bounds from those.
3066 let derived_region_bounds = object_region_bounds(tcx, existential_predicates);
3068 // If there are no derived region bounds, then report back that we
3069 // can find no region bound. The caller will use the default.
3070 if derived_region_bounds.is_empty() {
3074 // If any of the derived region bounds are 'static, that is always
3076 if derived_region_bounds.iter().any(|r| r.is_static()) {
3077 return Some(tcx.lifetimes.re_static);
3080 // Determine whether there is exactly one unique region in the set
3081 // of derived region bounds. If so, use that. Otherwise, report an
3083 let r = derived_region_bounds[0];
3084 if derived_region_bounds[1..].iter().any(|r1| r != *r1) {
3085 tcx.sess.emit_err(AmbiguousLifetimeBound { span });
3090 /// Make sure that we are in the condition to suggest the blanket implementation.
3091 fn maybe_lint_blanket_trait_impl(&self, self_ty: &hir::Ty<'_>, diag: &mut Diagnostic) {
3092 let tcx = self.tcx();
3093 let parent_id = tcx.hir().get_parent_item(self_ty.hir_id).def_id;
3094 if let hir::Node::Item(hir::Item {
3096 hir::ItemKind::Impl(hir::Impl {
3097 self_ty: impl_self_ty, of_trait: Some(of_trait_ref), generics, ..
3100 }) = tcx.hir().get_by_def_id(parent_id) && self_ty.hir_id == impl_self_ty.hir_id
3102 if !of_trait_ref.trait_def_id().map_or(false, |def_id| def_id.is_local()) {
3105 let of_trait_span = of_trait_ref.path.span;
3106 // make sure that we are not calling unwrap to abort during the compilation
3107 let Ok(impl_trait_name) = tcx.sess.source_map().span_to_snippet(self_ty.span) else { return; };
3108 let Ok(of_trait_name) = tcx.sess.source_map().span_to_snippet(of_trait_span) else { return; };
3109 // check if the trait has generics, to make a correct suggestion
3110 let param_name = generics.params.next_type_param_name(None);
3112 let add_generic_sugg = if let Some(span) = generics.span_for_param_suggestion() {
3113 (span, format!(", {}: {}", param_name, impl_trait_name))
3115 (generics.span, format!("<{}: {}>", param_name, impl_trait_name))
3117 diag.multipart_suggestion(
3118 format!("alternatively use a blanket \
3119 implementation to implement `{of_trait_name}` for \
3120 all types that also implement `{impl_trait_name}`"),
3122 (self_ty.span, param_name),
3125 Applicability::MaybeIncorrect,
3130 fn maybe_lint_bare_trait(&self, self_ty: &hir::Ty<'_>, in_path: bool) {
3131 let tcx = self.tcx();
3132 if let hir::TyKind::TraitObject([poly_trait_ref, ..], _, TraitObjectSyntax::None) =
3135 let needs_bracket = in_path
3139 .span_to_prev_source(self_ty.span)
3141 .map_or(false, |s| s.trim_end().ends_with('<'));
3143 let is_global = poly_trait_ref.trait_ref.path.is_global();
3145 let mut sugg = Vec::from_iter([(
3146 self_ty.span.shrink_to_lo(),
3149 if needs_bracket { "<" } else { "" },
3150 if is_global { "(" } else { "" },
3154 if is_global || needs_bracket {
3156 self_ty.span.shrink_to_hi(),
3159 if is_global { ")" } else { "" },
3160 if needs_bracket { ">" } else { "" },
3165 if self_ty.span.edition() >= Edition::Edition2021 {
3166 let msg = "trait objects must include the `dyn` keyword";
3167 let label = "add `dyn` keyword before this trait";
3169 rustc_errors::struct_span_err!(tcx.sess, self_ty.span, E0782, "{}", msg);
3170 diag.multipart_suggestion_verbose(label, sugg, Applicability::MachineApplicable);
3171 // check if the impl trait that we are considering is a impl of a local trait
3172 self.maybe_lint_blanket_trait_impl(&self_ty, &mut diag);
3175 let msg = "trait objects without an explicit `dyn` are deprecated";
3176 tcx.struct_span_lint_hir(
3182 lint.multipart_suggestion_verbose(
3185 Applicability::MachineApplicable,
3187 self.maybe_lint_blanket_trait_impl(&self_ty, lint);