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