rustc_trait_selection/traits/
dyn_compatibility.rs

1//! "Dyn-compatibility"[^1] refers to the ability for a trait to be converted
2//! to a trait object. In general, traits may only be converted to a trait
3//! object if certain criteria are met.
4//!
5//! [^1]: Formerly known as "object safety".
6
7use std::ops::ControlFlow;
8
9use rustc_errors::FatalError;
10use rustc_hir::attrs::AttributeKind;
11use rustc_hir::def_id::DefId;
12use rustc_hir::{self as hir, LangItem, find_attr};
13use rustc_middle::query::Providers;
14use rustc_middle::ty::{
15    self, EarlyBinder, GenericArgs, Ty, TyCtxt, TypeFoldable, TypeFolder, TypeSuperFoldable,
16    TypeSuperVisitable, TypeVisitable, TypeVisitableExt, TypeVisitor, TypingMode, Upcast,
17    elaborate,
18};
19use rustc_span::{DUMMY_SP, Span};
20use smallvec::SmallVec;
21use tracing::{debug, instrument};
22
23use super::elaborate;
24use crate::infer::TyCtxtInferExt;
25pub use crate::traits::DynCompatibilityViolation;
26use crate::traits::query::evaluate_obligation::InferCtxtExt;
27use crate::traits::{
28    AssocConstViolation, MethodViolation, Obligation, ObligationCause,
29    normalize_param_env_or_error, util,
30};
31
32/// Returns the dyn-compatibility violations that affect HIR ty lowering.
33///
34/// Currently that is `Self` in supertraits. This is needed
35/// because `dyn_compatibility_violations` can't be used during
36/// type collection, as type collection is needed for `dyn_compatibility_violations` itself.
37x;#[instrument(level = "debug", skip(tcx), ret)]
38pub fn hir_ty_lowering_dyn_compatibility_violations(
39    tcx: TyCtxt<'_>,
40    trait_def_id: DefId,
41) -> Vec<DynCompatibilityViolation> {
42    debug_assert!(tcx.generics_of(trait_def_id).has_self);
43    elaborate::supertrait_def_ids(tcx, trait_def_id)
44        .map(|def_id| predicates_reference_self(tcx, def_id, true))
45        .filter(|spans| !spans.is_empty())
46        .map(DynCompatibilityViolation::SupertraitSelf)
47        .collect()
48}
49
50fn dyn_compatibility_violations(
51    tcx: TyCtxt<'_>,
52    trait_def_id: DefId,
53) -> &'_ [DynCompatibilityViolation] {
54    if true {
    if !tcx.generics_of(trait_def_id).has_self {
        ::core::panicking::panic("assertion failed: tcx.generics_of(trait_def_id).has_self")
    };
};debug_assert!(tcx.generics_of(trait_def_id).has_self);
55    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:55",
                        "rustc_trait_selection::traits::dyn_compatibility",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
                        ::tracing_core::__macro_support::Option::Some(55u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("dyn_compatibility_violations: {0:?}",
                                                    trait_def_id) as &dyn Value))])
            });
    } else { ; }
};debug!("dyn_compatibility_violations: {:?}", trait_def_id);
56    tcx.arena.alloc_from_iter(
57        elaborate::supertrait_def_ids(tcx, trait_def_id)
58            .flat_map(|def_id| dyn_compatibility_violations_for_trait(tcx, def_id)),
59    )
60}
61
62fn is_dyn_compatible(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
63    tcx.dyn_compatibility_violations(trait_def_id).is_empty()
64}
65
66/// We say a method is *vtable safe* if it can be invoked on a trait
67/// object. Note that dyn-compatible traits can have some
68/// non-vtable-safe methods, so long as they require `Self: Sized` or
69/// otherwise ensure that they cannot be used when `Self = Trait`.
70pub fn is_vtable_safe_method(tcx: TyCtxt<'_>, trait_def_id: DefId, method: ty::AssocItem) -> bool {
71    if true {
    if !tcx.generics_of(trait_def_id).has_self {
        ::core::panicking::panic("assertion failed: tcx.generics_of(trait_def_id).has_self")
    };
};debug_assert!(tcx.generics_of(trait_def_id).has_self);
72    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:72",
                        "rustc_trait_selection::traits::dyn_compatibility",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
                        ::tracing_core::__macro_support::Option::Some(72u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("is_vtable_safe_method({0:?}, {1:?})",
                                                    trait_def_id, method) as &dyn Value))])
            });
    } else { ; }
};debug!("is_vtable_safe_method({:?}, {:?})", trait_def_id, method);
73    // Any method that has a `Self: Sized` bound cannot be called.
74    if tcx.generics_require_sized_self(method.def_id) {
75        return false;
76    }
77
78    virtual_call_violations_for_method(tcx, trait_def_id, method).is_empty()
79}
80
81x;#[instrument(level = "debug", skip(tcx), ret)]
82fn dyn_compatibility_violations_for_trait(
83    tcx: TyCtxt<'_>,
84    trait_def_id: DefId,
85) -> Vec<DynCompatibilityViolation> {
86    // Check assoc items for violations.
87    let mut violations: Vec<_> = tcx
88        .associated_items(trait_def_id)
89        .in_definition_order()
90        .flat_map(|&item| dyn_compatibility_violations_for_assoc_item(tcx, trait_def_id, item))
91        .collect();
92
93    // Check the trait itself.
94    if trait_has_sized_self(tcx, trait_def_id) {
95        // We don't want to include the requirement from `Sized` itself to be `Sized` in the list.
96        let spans = get_sized_bounds(tcx, trait_def_id);
97        violations.push(DynCompatibilityViolation::SizedSelf(spans));
98    } else if let Some(span) = tcx.trait_def(trait_def_id).force_dyn_incompatible {
99        violations.push(DynCompatibilityViolation::ExplicitlyDynIncompatible([span].into()));
100    }
101
102    let spans = predicates_reference_self(tcx, trait_def_id, false);
103    if !spans.is_empty() {
104        violations.push(DynCompatibilityViolation::SupertraitSelf(spans));
105    }
106    let spans = bounds_reference_self(tcx, trait_def_id);
107    if !spans.is_empty() {
108        violations.push(DynCompatibilityViolation::SupertraitSelf(spans));
109    }
110    let spans = super_predicates_have_non_lifetime_binders(tcx, trait_def_id);
111    if !spans.is_empty() {
112        violations.push(DynCompatibilityViolation::SupertraitNonLifetimeBinder(spans));
113    }
114    let spans = super_predicates_are_unconditionally_const(tcx, trait_def_id);
115    if !spans.is_empty() {
116        violations.push(DynCompatibilityViolation::SupertraitConst(spans));
117    }
118
119    violations
120}
121
122fn sized_trait_bound_spans<'tcx>(
123    tcx: TyCtxt<'tcx>,
124    bounds: hir::GenericBounds<'tcx>,
125) -> impl 'tcx + Iterator<Item = Span> {
126    bounds.iter().filter_map(move |b| match b {
127        hir::GenericBound::Trait(trait_ref)
128            if trait_has_sized_self(
129                tcx,
130                trait_ref.trait_ref.trait_def_id().unwrap_or_else(|| FatalError.raise()),
131            ) =>
132        {
133            // Fetch spans for supertraits that are `Sized`: `trait T: Super`
134            Some(trait_ref.span)
135        }
136        _ => None,
137    })
138}
139
140fn get_sized_bounds(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
141    tcx.hir_get_if_local(trait_def_id)
142        .and_then(|node| match node {
143            hir::Node::Item(hir::Item {
144                kind: hir::ItemKind::Trait(.., generics, bounds, _),
145                ..
146            }) => Some(
147                generics
148                    .predicates
149                    .iter()
150                    .filter_map(|pred| {
151                        match pred.kind {
152                            hir::WherePredicateKind::BoundPredicate(pred)
153                                if pred.bounded_ty.hir_id.owner.to_def_id() == trait_def_id =>
154                            {
155                                // Fetch spans for trait bounds that are Sized:
156                                // `trait T where Self: Pred`
157                                Some(sized_trait_bound_spans(tcx, pred.bounds))
158                            }
159                            _ => None,
160                        }
161                    })
162                    .flatten()
163                    // Fetch spans for supertraits that are `Sized`: `trait T: Super`.
164                    .chain(sized_trait_bound_spans(tcx, bounds))
165                    .collect::<SmallVec<[Span; 1]>>(),
166            ),
167            _ => None,
168        })
169        .unwrap_or_else(SmallVec::new)
170}
171
172fn predicates_reference_self(
173    tcx: TyCtxt<'_>,
174    trait_def_id: DefId,
175    supertraits_only: bool,
176) -> SmallVec<[Span; 1]> {
177    let trait_ref = ty::Binder::dummy(ty::TraitRef::identity(tcx, trait_def_id));
178    let predicates = if supertraits_only {
179        tcx.explicit_super_predicates_of(trait_def_id).skip_binder()
180    } else {
181        tcx.predicates_of(trait_def_id).predicates
182    };
183    predicates
184        .iter()
185        .map(|&(predicate, sp)| (predicate.instantiate_supertrait(tcx, trait_ref), sp))
186        .filter_map(|(clause, sp)| {
187            // Super predicates cannot allow self projections, since they're
188            // impossible to make into existential bounds without eager resolution
189            // or something.
190            // e.g. `trait A: B<Item = Self::Assoc>`.
191            predicate_references_self(tcx, trait_def_id, clause, sp, AllowSelfProjections::No)
192        })
193        .collect()
194}
195
196fn bounds_reference_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> SmallVec<[Span; 1]> {
197    tcx.associated_items(trait_def_id)
198        .in_definition_order()
199        // We're only looking at associated type bounds
200        .filter(|item| item.is_type())
201        // Ignore GATs with `Self: Sized`
202        .filter(|item| !tcx.generics_require_sized_self(item.def_id))
203        .flat_map(|item| tcx.explicit_item_bounds(item.def_id).iter_identity_copied())
204        .filter_map(|(clause, sp)| {
205            // Item bounds *can* have self projections, since they never get
206            // their self type erased.
207            predicate_references_self(tcx, trait_def_id, clause, sp, AllowSelfProjections::Yes)
208        })
209        .collect()
210}
211
212fn predicate_references_self<'tcx>(
213    tcx: TyCtxt<'tcx>,
214    trait_def_id: DefId,
215    predicate: ty::Clause<'tcx>,
216    sp: Span,
217    allow_self_projections: AllowSelfProjections,
218) -> Option<Span> {
219    match predicate.kind().skip_binder() {
220        ty::ClauseKind::Trait(ref data) => {
221            // In the case of a trait predicate, we can skip the "self" type.
222            data.trait_ref.args[1..].iter().any(|&arg| contains_illegal_self_type_reference(tcx, trait_def_id, arg, allow_self_projections)).then_some(sp)
223        }
224        ty::ClauseKind::Projection(ref data) => {
225            // And similarly for projections. This should be redundant with
226            // the previous check because any projection should have a
227            // matching `Trait` predicate with the same inputs, but we do
228            // the check to be safe.
229            //
230            // It's also won't be redundant if we allow type-generic associated
231            // types for trait objects.
232            //
233            // Note that we *do* allow projection *outputs* to contain
234            // `Self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
235            // we just require the user to specify *both* outputs
236            // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
237            //
238            // This is ALT2 in issue #56288, see that for discussion of the
239            // possible alternatives.
240            data.projection_term.args[1..].iter().any(|&arg| contains_illegal_self_type_reference(tcx, trait_def_id, arg, allow_self_projections)).then_some(sp)
241        }
242        ty::ClauseKind::ConstArgHasType(_ct, ty) => contains_illegal_self_type_reference(tcx, trait_def_id, ty, allow_self_projections).then_some(sp),
243
244        ty::ClauseKind::WellFormed(..)
245        | ty::ClauseKind::TypeOutlives(..)
246        | ty::ClauseKind::RegionOutlives(..)
247        // FIXME(generic_const_exprs): this can mention `Self`
248        | ty::ClauseKind::ConstEvaluatable(..)
249        | ty::ClauseKind::HostEffect(..)
250        | ty::ClauseKind::UnstableFeature(_)
251         => None,
252    }
253}
254
255fn super_predicates_have_non_lifetime_binders(
256    tcx: TyCtxt<'_>,
257    trait_def_id: DefId,
258) -> SmallVec<[Span; 1]> {
259    tcx.explicit_super_predicates_of(trait_def_id)
260        .iter_identity_copied()
261        .filter_map(|(pred, span)| pred.has_non_region_bound_vars().then_some(span))
262        .collect()
263}
264
265/// Checks for `const Trait` supertraits. We're okay with `[const] Trait`,
266/// supertraits since for a non-const instantiation of that trait, the
267/// conditionally-const supertrait is also not required to be const.
268fn super_predicates_are_unconditionally_const(
269    tcx: TyCtxt<'_>,
270    trait_def_id: DefId,
271) -> SmallVec<[Span; 1]> {
272    tcx.explicit_super_predicates_of(trait_def_id)
273        .iter_identity_copied()
274        .filter_map(|(pred, span)| {
275            if let ty::ClauseKind::HostEffect(_) = pred.kind().skip_binder() {
276                Some(span)
277            } else {
278                None
279            }
280        })
281        .collect()
282}
283
284fn trait_has_sized_self(tcx: TyCtxt<'_>, trait_def_id: DefId) -> bool {
285    tcx.generics_require_sized_self(trait_def_id)
286}
287
288fn generics_require_sized_self(tcx: TyCtxt<'_>, def_id: DefId) -> bool {
289    let Some(sized_def_id) = tcx.lang_items().sized_trait() else {
290        return false; /* No Sized trait, can't require it! */
291    };
292
293    // Search for a predicate like `Self: Sized` amongst the trait bounds.
294    let predicates = tcx.predicates_of(def_id);
295    let predicates = predicates.instantiate_identity(tcx).predicates;
296    elaborate(tcx, predicates).any(|pred| match pred.kind().skip_binder() {
297        ty::ClauseKind::Trait(ref trait_pred) => {
298            trait_pred.def_id() == sized_def_id && trait_pred.self_ty().is_param(0)
299        }
300        ty::ClauseKind::RegionOutlives(_)
301        | ty::ClauseKind::TypeOutlives(_)
302        | ty::ClauseKind::Projection(_)
303        | ty::ClauseKind::ConstArgHasType(_, _)
304        | ty::ClauseKind::WellFormed(_)
305        | ty::ClauseKind::ConstEvaluatable(_)
306        | ty::ClauseKind::UnstableFeature(_)
307        | ty::ClauseKind::HostEffect(..) => false,
308    })
309}
310
311x;#[instrument(level = "debug", skip(tcx), ret)]
312pub fn dyn_compatibility_violations_for_assoc_item(
313    tcx: TyCtxt<'_>,
314    trait_def_id: DefId,
315    item: ty::AssocItem,
316) -> Vec<DynCompatibilityViolation> {
317    // Any item that has a `Self: Sized` requisite is otherwise exempt from the regulations.
318    if tcx.generics_require_sized_self(item.def_id) {
319        return Vec::new();
320    }
321
322    let span = || item.ident(tcx).span;
323
324    match item.kind {
325        ty::AssocKind::Const { name } => {
326            // We will permit type associated consts if they are explicitly mentioned in the
327            // trait object type. We can't check this here, as here we only check if it is
328            // guaranteed to not be possible.
329
330            let mut errors = Vec::new();
331
332            if tcx.features().min_generic_const_args() {
333                if !tcx.generics_of(item.def_id).is_own_empty() {
334                    errors.push(AssocConstViolation::Generic);
335                } else if !find_attr!(tcx.get_all_attrs(item.def_id), AttributeKind::TypeConst(_)) {
336                    errors.push(AssocConstViolation::NonType);
337                }
338
339                let ty = ty::Binder::dummy(tcx.type_of(item.def_id).instantiate_identity());
340                if contains_illegal_self_type_reference(
341                    tcx,
342                    trait_def_id,
343                    ty,
344                    AllowSelfProjections::Yes,
345                ) {
346                    errors.push(AssocConstViolation::TypeReferencesSelf);
347                }
348            } else {
349                errors.push(AssocConstViolation::FeatureNotEnabled);
350            }
351
352            errors
353                .into_iter()
354                .map(|error| DynCompatibilityViolation::AssocConst(name, error, span()))
355                .collect()
356        }
357        ty::AssocKind::Fn { name, .. } => {
358            virtual_call_violations_for_method(tcx, trait_def_id, item)
359                .into_iter()
360                .map(|v| {
361                    let node = tcx.hir_get_if_local(item.def_id);
362                    // Get an accurate span depending on the violation.
363                    let span = match (&v, node) {
364                        (MethodViolation::ReferencesSelfInput(Some(span)), _) => *span,
365                        (MethodViolation::UndispatchableReceiver(Some(span)), _) => *span,
366                        (MethodViolation::ReferencesImplTraitInTrait(span), _) => *span,
367                        (MethodViolation::ReferencesSelfOutput, Some(node)) => {
368                            node.fn_decl().map_or(item.ident(tcx).span, |decl| decl.output.span())
369                        }
370                        _ => span(),
371                    };
372
373                    DynCompatibilityViolation::Method(name, v, span)
374                })
375                .collect()
376        }
377        ty::AssocKind::Type { data } => {
378            if !tcx.generics_of(item.def_id).is_own_empty()
379                && let ty::AssocTypeData::Normal(name) = data
380            {
381                vec![DynCompatibilityViolation::GenericAssocTy(name, span())]
382            } else {
383                // We will permit associated types if they are explicitly mentioned in the trait
384                // object type. We can't check this here, as here we only check if it is
385                // guaranteed to not be possible.
386                Vec::new()
387            }
388        }
389    }
390}
391
392/// Returns `Some(_)` if this method cannot be called on a trait
393/// object; this does not necessarily imply that the enclosing trait
394/// is dyn-incompatible, because the method might have a where clause
395/// `Self: Sized`.
396fn virtual_call_violations_for_method<'tcx>(
397    tcx: TyCtxt<'tcx>,
398    trait_def_id: DefId,
399    method: ty::AssocItem,
400) -> Vec<MethodViolation> {
401    let sig = tcx.fn_sig(method.def_id).instantiate_identity();
402
403    // The method's first parameter must be named `self`
404    if !method.is_method() {
405        let sugg = if let Some(hir::Node::TraitItem(hir::TraitItem {
406            generics,
407            kind: hir::TraitItemKind::Fn(sig, _),
408            ..
409        })) = tcx.hir_get_if_local(method.def_id).as_ref()
410        {
411            let sm = tcx.sess.source_map();
412            Some((
413                (
414                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("&self{0}",
                if sig.decl.inputs.is_empty() { "" } else { ", " }))
    })format!("&self{}", if sig.decl.inputs.is_empty() { "" } else { ", " }),
415                    sm.span_through_char(sig.span, '(').shrink_to_hi(),
416                ),
417                (
418                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0} Self: Sized",
                generics.add_where_or_trailing_comma()))
    })format!("{} Self: Sized", generics.add_where_or_trailing_comma()),
419                    generics.tail_span_for_predicate_suggestion(),
420                ),
421            ))
422        } else {
423            None
424        };
425
426        // Not having `self` parameter messes up the later checks,
427        // so we need to return instead of pushing
428        return <[_]>::into_vec(::alloc::boxed::box_new([MethodViolation::StaticMethod(sugg)]))vec![MethodViolation::StaticMethod(sugg)];
429    }
430
431    let mut errors = Vec::new();
432
433    for (i, &input_ty) in sig.skip_binder().inputs().iter().enumerate().skip(1) {
434        if contains_illegal_self_type_reference(
435            tcx,
436            trait_def_id,
437            sig.rebind(input_ty),
438            AllowSelfProjections::Yes,
439        ) {
440            let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
441                kind: hir::TraitItemKind::Fn(sig, _),
442                ..
443            })) = tcx.hir_get_if_local(method.def_id).as_ref()
444            {
445                Some(sig.decl.inputs[i].span)
446            } else {
447                None
448            };
449            errors.push(MethodViolation::ReferencesSelfInput(span));
450        }
451    }
452    if contains_illegal_self_type_reference(
453        tcx,
454        trait_def_id,
455        sig.output(),
456        AllowSelfProjections::Yes,
457    ) {
458        errors.push(MethodViolation::ReferencesSelfOutput);
459    }
460    if let Some(error) = contains_illegal_impl_trait_in_trait(tcx, method.def_id, sig.output()) {
461        errors.push(error);
462    }
463    if sig.skip_binder().c_variadic {
464        errors.push(MethodViolation::CVariadic);
465    }
466
467    // We can't monomorphize things like `fn foo<A>(...)`.
468    let own_counts = tcx.generics_of(method.def_id).own_counts();
469    if own_counts.types > 0 || own_counts.consts > 0 {
470        errors.push(MethodViolation::Generic);
471    }
472
473    let receiver_ty = tcx.liberate_late_bound_regions(method.def_id, sig.input(0));
474
475    // `self: Self` can't be dispatched on.
476    // However, this is considered dyn compatible. We allow it as a special case here.
477    // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
478    // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
479    if receiver_ty != tcx.types.self_param {
480        if !receiver_is_dispatchable(tcx, method, receiver_ty) {
481            let span = if let Some(hir::Node::TraitItem(hir::TraitItem {
482                kind: hir::TraitItemKind::Fn(sig, _),
483                ..
484            })) = tcx.hir_get_if_local(method.def_id).as_ref()
485            {
486                Some(sig.decl.inputs[0].span)
487            } else {
488                None
489            };
490            errors.push(MethodViolation::UndispatchableReceiver(span));
491        } else {
492            // We confirm that the `receiver_is_dispatchable` is accurate later,
493            // see `check_receiver_correct`. It should be kept in sync with this code.
494        }
495    }
496
497    // NOTE: This check happens last, because it results in a lint, and not a
498    // hard error.
499    if tcx.predicates_of(method.def_id).predicates.iter().any(|&(pred, _span)| {
500        // dyn Trait is okay:
501        //
502        //     trait Trait {
503        //         fn f(&self) where Self: 'static;
504        //     }
505        //
506        // because a trait object can't claim to live longer than the concrete
507        // type. If the lifetime bound holds on dyn Trait then it's guaranteed
508        // to hold as well on the concrete type.
509        if pred.as_type_outlives_clause().is_some() {
510            return false;
511        }
512
513        // dyn Trait is okay:
514        //
515        //     auto trait AutoTrait {}
516        //
517        //     trait Trait {
518        //         fn f(&self) where Self: AutoTrait;
519        //     }
520        //
521        // because `impl AutoTrait for dyn Trait` is disallowed by coherence.
522        // Traits with a default impl are implemented for a trait object if and
523        // only if the autotrait is one of the trait object's trait bounds, like
524        // in `dyn Trait + AutoTrait`. This guarantees that trait objects only
525        // implement auto traits if the underlying type does as well.
526        if let ty::ClauseKind::Trait(ty::TraitPredicate {
527            trait_ref: pred_trait_ref,
528            polarity: ty::PredicatePolarity::Positive,
529        }) = pred.kind().skip_binder()
530            && pred_trait_ref.self_ty() == tcx.types.self_param
531            && tcx.trait_is_auto(pred_trait_ref.def_id)
532        {
533            // Consider bounds like `Self: Bound<Self>`. Auto traits are not
534            // allowed to have generic parameters so `auto trait Bound<T> {}`
535            // would already have reported an error at the definition of the
536            // auto trait.
537            if pred_trait_ref.args.len() != 1 {
538                if !tcx.dcx().has_errors().is_some() {
    {
        ::core::panicking::panic_fmt(format_args!("auto traits cannot have generic parameters"));
    }
};assert!(
539                    tcx.dcx().has_errors().is_some(),
540                    "auto traits cannot have generic parameters"
541                );
542            }
543            return false;
544        }
545
546        contains_illegal_self_type_reference(tcx, trait_def_id, pred, AllowSelfProjections::Yes)
547    }) {
548        errors.push(MethodViolation::WhereClauseReferencesSelf);
549    }
550
551    errors
552}
553
554/// Performs a type instantiation to produce the version of `receiver_ty` when `Self = self_ty`.
555/// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
556fn receiver_for_self_ty<'tcx>(
557    tcx: TyCtxt<'tcx>,
558    receiver_ty: Ty<'tcx>,
559    self_ty: Ty<'tcx>,
560    method_def_id: DefId,
561) -> Ty<'tcx> {
562    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:562",
                        "rustc_trait_selection::traits::dyn_compatibility",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
                        ::tracing_core::__macro_support::Option::Some(562u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("receiver_for_self_ty({0:?}, {1:?}, {2:?})",
                                                    receiver_ty, self_ty, method_def_id) as &dyn Value))])
            });
    } else { ; }
};debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
563    let args = GenericArgs::for_item(tcx, method_def_id, |param, _| {
564        if param.index == 0 { self_ty.into() } else { tcx.mk_param_from_def(param) }
565    });
566
567    let result = EarlyBinder::bind(receiver_ty).instantiate(tcx, args);
568    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:568",
                        "rustc_trait_selection::traits::dyn_compatibility",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
                        ::tracing_core::__macro_support::Option::Some(568u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("receiver_for_self_ty({0:?}, {1:?}, {2:?}) = {3:?}",
                                                    receiver_ty, self_ty, method_def_id, result) as
                                            &dyn Value))])
            });
    } else { ; }
};debug!(
569        "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
570        receiver_ty, self_ty, method_def_id, result
571    );
572    result
573}
574
575/// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
576/// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
577/// in the following way:
578/// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
579/// - require the following bound:
580///
581///   ```ignore (not-rust)
582///   Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
583///   ```
584///
585///   where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
586///   (instantiation notation).
587///
588/// Some examples of receiver types and their required obligation:
589/// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
590/// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
591/// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
592///
593/// The only case where the receiver is not dispatchable, but is still a valid receiver
594/// type (just not dyn compatible), is when there is more than one level of pointer indirection.
595/// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
596/// is no way, or at least no inexpensive way, to coerce the receiver from the version where
597/// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
598/// contained by the trait object, because the object that needs to be coerced is behind
599/// a pointer.
600///
601/// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result in
602/// a new check that `Trait` is dyn-compatible, creating a cycle.
603/// Instead, we emulate a placeholder by introducing a new type parameter `U` such that
604/// `Self: Unsize<U>` and `U: Trait + MetaSized`, and use `U` in place of `dyn Trait`.
605///
606/// Written as a chalk-style query:
607/// ```ignore (not-rust)
608/// forall (U: Trait + MetaSized) {
609///     if (Self: Unsize<U>) {
610///         Receiver: DispatchFromDyn<Receiver[Self => U]>
611///     }
612/// }
613/// ```
614/// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
615/// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
616/// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
617//
618// FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
619// fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
620// `self: Wrapper<Self>`.
621fn receiver_is_dispatchable<'tcx>(
622    tcx: TyCtxt<'tcx>,
623    method: ty::AssocItem,
624    receiver_ty: Ty<'tcx>,
625) -> bool {
626    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:626",
                        "rustc_trait_selection::traits::dyn_compatibility",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
                        ::tracing_core::__macro_support::Option::Some(626u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("receiver_is_dispatchable: method = {0:?}, receiver_ty = {1:?}",
                                                    method, receiver_ty) as &dyn Value))])
            });
    } else { ; }
};debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
627
628    let (Some(unsize_did), Some(dispatch_from_dyn_did)) =
629        (tcx.lang_items().unsize_trait(), tcx.lang_items().dispatch_from_dyn_trait())
630    else {
631        {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs:631",
                        "rustc_trait_selection::traits::dyn_compatibility",
                        ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("compiler/rustc_trait_selection/src/traits/dyn_compatibility.rs"),
                        ::tracing_core::__macro_support::Option::Some(631u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_trait_selection::traits::dyn_compatibility"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                let mut iter = __CALLSITE.metadata().fields().iter();
                __CALLSITE.metadata().fields().value_set(&[(&::tracing::__macro_support::Iterator::next(&mut iter).expect("FieldSet corrupted (this is a bug)"),
                                    ::tracing::__macro_support::Option::Some(&format_args!("receiver_is_dispatchable: Missing `Unsize` or `DispatchFromDyn` traits")
                                            as &dyn Value))])
            });
    } else { ; }
};debug!("receiver_is_dispatchable: Missing `Unsize` or `DispatchFromDyn` traits");
632        return false;
633    };
634
635    // the type `U` in the query
636    // use a bogus type parameter to mimic a forall(U) query using u32::MAX for now.
637    let unsized_self_ty: Ty<'tcx> =
638        Ty::new_param(tcx, u32::MAX, rustc_span::sym::RustaceansAreAwesome);
639
640    // `Receiver[Self => U]`
641    let unsized_receiver_ty =
642        receiver_for_self_ty(tcx, receiver_ty, unsized_self_ty, method.def_id);
643
644    // create a modified param env, with `Self: Unsize<U>` and `U: Trait` (and all of
645    // its supertraits) added to caller bounds. `U: MetaSized` is already implied here.
646    let param_env = {
647        // N.B. We generally want to emulate the construction of the `unnormalized_param_env`
648        // in the param-env query here. The fact that we don't just start with the clauses
649        // in the param-env of the method is because those are already normalized, and mixing
650        // normalized and unnormalized copies of predicates in `normalize_param_env_or_error`
651        // will cause ambiguity that the user can't really avoid.
652        //
653        // We leave out certain complexities of the param-env query here. Specifically, we:
654        // 1. Do not add `[const]` bounds since there are no `dyn const Trait`s.
655        // 2. Do not add RPITIT self projection bounds for defaulted methods, since we
656        //    are not constructing a param-env for "inside" of the body of the defaulted
657        //    method, so we don't really care about projecting to a specific RPIT type,
658        //    and because RPITITs are not dyn compatible (yet).
659        let mut predicates = tcx.predicates_of(method.def_id).instantiate_identity(tcx).predicates;
660
661        // Self: Unsize<U>
662        let unsize_predicate =
663            ty::TraitRef::new(tcx, unsize_did, [tcx.types.self_param, unsized_self_ty]);
664        predicates.push(unsize_predicate.upcast(tcx));
665
666        // U: Trait<Arg1, ..., ArgN>
667        let trait_def_id = method.trait_container(tcx).unwrap();
668        let args = GenericArgs::for_item(tcx, trait_def_id, |param, _| {
669            if param.index == 0 { unsized_self_ty.into() } else { tcx.mk_param_from_def(param) }
670        });
671        let trait_predicate = ty::TraitRef::new_from_args(tcx, trait_def_id, args);
672        predicates.push(trait_predicate.upcast(tcx));
673
674        let meta_sized_predicate = {
675            let meta_sized_did = tcx.require_lang_item(LangItem::MetaSized, DUMMY_SP);
676            ty::TraitRef::new(tcx, meta_sized_did, [unsized_self_ty]).upcast(tcx)
677        };
678        predicates.push(meta_sized_predicate);
679
680        normalize_param_env_or_error(
681            tcx,
682            ty::ParamEnv::new(tcx.mk_clauses(&predicates)),
683            ObligationCause::dummy_with_span(tcx.def_span(method.def_id)),
684        )
685    };
686
687    // Receiver: DispatchFromDyn<Receiver[Self => U]>
688    let obligation = {
689        let predicate =
690            ty::TraitRef::new(tcx, dispatch_from_dyn_did, [receiver_ty, unsized_receiver_ty]);
691
692        Obligation::new(tcx, ObligationCause::dummy(), param_env, predicate)
693    };
694
695    let infcx = tcx.infer_ctxt().build(TypingMode::non_body_analysis());
696    // the receiver is dispatchable iff the obligation holds
697    infcx.predicate_must_hold_modulo_regions(&obligation)
698}
699
700#[derive(#[automatically_derived]
impl ::core::marker::Copy for AllowSelfProjections { }Copy, #[automatically_derived]
impl ::core::clone::Clone for AllowSelfProjections {
    #[inline]
    fn clone(&self) -> AllowSelfProjections { *self }
}Clone)]
701enum AllowSelfProjections {
702    Yes,
703    No,
704}
705
706/// Check if the given value contains illegal `Self` references.
707///
708/// This is somewhat subtle. In general, we want to forbid references to `Self` in the
709/// argument and return types, since the value of `Self` is erased.
710///
711/// However, there is one exception: It is ok to reference `Self` in order to access an
712/// associated type of the current trait, since we retain the value of those associated
713/// types in the trait object type itself.
714///
715/// The same thing holds for associated consts under feature `min_generic_const_args`.
716///
717/// ```rust,ignore (example)
718/// trait SuperTrait {
719///     type X;
720/// }
721///
722/// trait Trait : SuperTrait {
723///     type Y;
724///     fn foo(&self, x: Self) // bad
725///     fn foo(&self) -> Self // bad
726///     fn foo(&self) -> Option<Self> // bad
727///     fn foo(&self) -> Self::Y // OK, desugars to next example
728///     fn foo(&self) -> <Self as Trait>::Y // OK
729///     fn foo(&self) -> Self::X // OK, desugars to next example
730///     fn foo(&self) -> <Self as SuperTrait>::X // OK
731/// }
732/// ```
733///
734/// However, it is not as simple as allowing `Self` in a projected
735/// type, because there are illegal ways to use `Self` as well:
736///
737/// ```rust,ignore (example)
738/// trait Trait : SuperTrait {
739///     ...
740///     fn foo(&self) -> <Self as SomeOtherTrait>::X;
741/// }
742/// ```
743///
744/// Here we will not have the type of `X` recorded in the
745/// object type, and we cannot resolve `Self as SomeOtherTrait`
746/// without knowing what `Self` is.
747fn contains_illegal_self_type_reference<'tcx, T: TypeVisitable<TyCtxt<'tcx>>>(
748    tcx: TyCtxt<'tcx>,
749    trait_def_id: DefId,
750    value: T,
751    allow_self_projections: AllowSelfProjections,
752) -> bool {
753    value
754        .visit_with(&mut IllegalSelfTypeVisitor {
755            tcx,
756            trait_def_id,
757            supertraits: None,
758            allow_self_projections,
759        })
760        .is_break()
761}
762
763struct IllegalSelfTypeVisitor<'tcx> {
764    tcx: TyCtxt<'tcx>,
765    trait_def_id: DefId,
766    supertraits: Option<Vec<ty::TraitRef<'tcx>>>,
767    allow_self_projections: AllowSelfProjections,
768}
769
770impl<'tcx> IllegalSelfTypeVisitor<'tcx> {
771    fn is_supertrait_of_current_trait(&mut self, trait_ref: ty::TraitRef<'tcx>) -> bool {
772        // Compute supertraits of current trait lazily.
773        let supertraits = self.supertraits.get_or_insert_with(|| {
774            util::supertraits(
775                self.tcx,
776                ty::Binder::dummy(ty::TraitRef::identity(self.tcx, self.trait_def_id)),
777            )
778            .map(|trait_ref| {
779                self.tcx.erase_and_anonymize_regions(
780                    self.tcx.instantiate_bound_regions_with_erased(trait_ref),
781                )
782            })
783            .collect()
784        });
785
786        // Determine whether the given trait ref is in fact a supertrait of the current trait.
787        // In that case, any derived projections are legal, because the term will be specified
788        // in the trait object type.
789        // Note that we can just use direct equality here because all of these types are part of
790        // the formal parameter listing, and hence there should be no inference variables.
791        let trait_ref = trait_ref
792            .fold_with(&mut EraseEscapingBoundRegions { tcx: self.tcx, binder: ty::INNERMOST });
793        supertraits.contains(&trait_ref)
794    }
795}
796
797impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IllegalSelfTypeVisitor<'tcx> {
798    type Result = ControlFlow<()>;
799
800    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
801        match ty.kind() {
802            ty::Param(_) => {
803                if ty == self.tcx.types.self_param {
804                    ControlFlow::Break(())
805                } else {
806                    ControlFlow::Continue(())
807                }
808            }
809            ty::Alias(ty::Projection, proj) if self.tcx.is_impl_trait_in_trait(proj.def_id) => {
810                // We'll deny these later in their own pass
811                ControlFlow::Continue(())
812            }
813            ty::Alias(ty::Projection, proj) => {
814                match self.allow_self_projections {
815                    AllowSelfProjections::Yes => {
816                        // Only walk contained types if the parent trait is not a supertrait.
817                        if self.is_supertrait_of_current_trait(proj.trait_ref(self.tcx)) {
818                            ControlFlow::Continue(())
819                        } else {
820                            ty.super_visit_with(self)
821                        }
822                    }
823                    AllowSelfProjections::No => ty.super_visit_with(self),
824                }
825            }
826            _ => ty.super_visit_with(self),
827        }
828    }
829
830    fn visit_const(&mut self, ct: ty::Const<'tcx>) -> Self::Result {
831        let ct = self.tcx.expand_abstract_consts(ct);
832
833        match ct.kind() {
834            ty::ConstKind::Unevaluated(proj) if self.tcx.features().min_generic_const_args() => {
835                match self.allow_self_projections {
836                    AllowSelfProjections::Yes => {
837                        let trait_def_id = self.tcx.parent(proj.def);
838                        let trait_ref = ty::TraitRef::from_assoc(self.tcx, trait_def_id, proj.args);
839
840                        // Only walk contained consts if the parent trait is not a supertrait.
841                        if self.is_supertrait_of_current_trait(trait_ref) {
842                            ControlFlow::Continue(())
843                        } else {
844                            ct.super_visit_with(self)
845                        }
846                    }
847                    AllowSelfProjections::No => ct.super_visit_with(self),
848                }
849            }
850            _ => ct.super_visit_with(self),
851        }
852    }
853}
854
855struct EraseEscapingBoundRegions<'tcx> {
856    tcx: TyCtxt<'tcx>,
857    binder: ty::DebruijnIndex,
858}
859
860impl<'tcx> TypeFolder<TyCtxt<'tcx>> for EraseEscapingBoundRegions<'tcx> {
861    fn cx(&self) -> TyCtxt<'tcx> {
862        self.tcx
863    }
864
865    fn fold_binder<T>(&mut self, t: ty::Binder<'tcx, T>) -> ty::Binder<'tcx, T>
866    where
867        T: TypeFoldable<TyCtxt<'tcx>>,
868    {
869        self.binder.shift_in(1);
870        let result = t.super_fold_with(self);
871        self.binder.shift_out(1);
872        result
873    }
874
875    fn fold_region(&mut self, r: ty::Region<'tcx>) -> ty::Region<'tcx> {
876        if let ty::ReBound(ty::BoundVarIndexKind::Bound(debruijn), _) = r.kind()
877            && debruijn < self.binder
878        {
879            r
880        } else {
881            self.tcx.lifetimes.re_erased
882        }
883    }
884}
885
886fn contains_illegal_impl_trait_in_trait<'tcx>(
887    tcx: TyCtxt<'tcx>,
888    fn_def_id: DefId,
889    ty: ty::Binder<'tcx, Ty<'tcx>>,
890) -> Option<MethodViolation> {
891    let ty = tcx.liberate_late_bound_regions(fn_def_id, ty);
892
893    if tcx.asyncness(fn_def_id).is_async() {
894        // Rendering the error as a separate `async-specific` message is better.
895        Some(MethodViolation::AsyncFn)
896    } else {
897        ty.visit_with(&mut IllegalRpititVisitor { tcx, allowed: None }).break_value()
898    }
899}
900
901struct IllegalRpititVisitor<'tcx> {
902    tcx: TyCtxt<'tcx>,
903    allowed: Option<ty::AliasTy<'tcx>>,
904}
905
906impl<'tcx> TypeVisitor<TyCtxt<'tcx>> for IllegalRpititVisitor<'tcx> {
907    type Result = ControlFlow<MethodViolation>;
908
909    fn visit_ty(&mut self, ty: Ty<'tcx>) -> Self::Result {
910        if let ty::Alias(ty::Projection, proj) = *ty.kind()
911            && Some(proj) != self.allowed
912            && self.tcx.is_impl_trait_in_trait(proj.def_id)
913        {
914            ControlFlow::Break(MethodViolation::ReferencesImplTraitInTrait(
915                self.tcx.def_span(proj.def_id),
916            ))
917        } else {
918            ty.super_visit_with(self)
919        }
920    }
921}
922
923pub(crate) fn provide(providers: &mut Providers) {
924    *providers = Providers {
925        dyn_compatibility_violations,
926        is_dyn_compatible,
927        generics_require_sized_self,
928        ..*providers
929    };
930}