Skip to main content

hir_ty/
dyn_compatibility.rs

1//! Compute the dyn-compatibility of a trait
2
3use std::ops::ControlFlow;
4
5use base_db::Crate;
6use hir_def::{
7    AssocItemId, ConstId, FunctionId, GenericDefId, HasModule, TraitId, TypeAliasId,
8    TypeOrConstParamId, TypeParamId,
9    attrs::AttrFlags,
10    hir::generics::{GenericParams, LocalTypeOrConstParamId},
11    nameres::assoc::TraitItems,
12    signatures::{FunctionSignature, TraitFlags, TraitSignature},
13    unstable_features::UnstableFeatures,
14};
15use rustc_type_ir::{
16    AliasTyKind, BoundVarIndexKind, ClauseKind, DebruijnIndex, Interner as _, PredicatePolarity,
17    TraitPredicate, TypeFoldable, TypeFolder, TypeSuperFoldable, TypeSuperVisitable as _,
18    TypeVisitable, TypeVisitableExt, TypeVisitor, Upcast,
19    elaborate::{self, elaborate},
20    inherent::{Clause as _, IntoKind},
21};
22use tracing::{debug, instrument};
23use triomphe::ThinArc;
24
25use crate::{
26    ImplTraitId,
27    db::HirDatabase,
28    lower::{GenericPredicates, SupertraitsInfo},
29    next_solver::{
30        AliasTy, Binder, Clause, Clauses, DbInterner, DefaultAny, EarlyBinder, GenericArgs,
31        ParamEnv, ParamTy, Region, RegionKind, TraitRef, Ty, TyKind, TypingMode, Unnormalized,
32        default_types,
33        infer::{
34            DbInternerInferExt,
35            traits::{Obligation, ObligationCause},
36        },
37        mk_param,
38    },
39};
40
41pub type DynCompatibilityViolations = ThinArc<(), DynCompatibilityViolation>;
42
43#[derive(Debug, Clone, PartialEq, Eq, Hash)]
44pub enum DynCompatibilityViolation {
45    /// Trait is marked `#[rustc_dyn_incompatible_trait]`.
46    ExplicitlyDynIncompatible,
47
48    /// `Self: Sized` declared on the trait.
49    SizedSelf,
50
51    /// Supertrait reference references `Self` an in illegal location
52    /// (e.g., `trait Foo : Bar<Self>`).
53    SupertraitSelf,
54
55    // Supertrait has a non-lifetime `for<T>` binder.
56    SupertraitNonLifetimeBinder,
57
58    // Trait has a `const Trait` supertrait.
59    SupertraitConst,
60
61    /// Method has something illegal.
62    Method(FunctionId, MethodViolation),
63
64    /// Associated constant is faulty.
65    AssocConst(ConstId, AssocConstViolation),
66
67    /// Generic associated type (GAT).
68    GenericAssocTy(TypeAliasId),
69
70    // This doesn't exist in rustc, but added for better visualization
71    HasNonCompatibleSuperTrait(TraitId, DynCompatibilityViolations),
72}
73
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
75pub enum AssocConstViolation {
76    /// Unstable feature `min_generic_const_args` wasn't enabled.
77    FeatureNotEnabled,
78
79    /// Not defined as a type-level associated const.
80    NonType,
81
82    /// Has own generic parameters (GAC).
83    Generic,
84
85    /// Its type mentions the `Self` type parameter.
86    TypeReferencesSelf,
87}
88
89#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
90pub enum MethodViolation {
91    /// e.g., `fn foo()`
92    StaticMethod,
93
94    /// e.g., `fn foo(&self, x: Self)`
95    ReferencesSelfInput,
96
97    /// e.g., `fn foo(&self) -> Self`
98    ReferencesSelfOutput,
99
100    /// e.g., `fn foo(&self) -> impl Sized`
101    ReferencesImplTraitInTrait,
102
103    /// e.g., `async fn foo(&self)`
104    AsyncFn,
105
106    /// e.g., `fn foo(&self) where Self: Clone`
107    WhereClauseReferencesSelf,
108
109    /// e.g., `fn foo<A>()`
110    Generic,
111
112    /// e.g., `fn (mut ap: ...)`
113    CVariadic,
114
115    /// the method's receiver (`self` argument) can't be dispatched on
116    UndispatchableReceiver,
117}
118
119struct LazyFeatures<'db> {
120    krate: Crate,
121    features: Option<&'db UnstableFeatures>,
122}
123
124impl<'db> LazyFeatures<'db> {
125    fn get(&mut self, db: &'db dyn HirDatabase) -> &'db UnstableFeatures {
126        self.features.get_or_insert_with(|| UnstableFeatures::query(db, self.krate))
127    }
128}
129
130#[salsa::tracked]
131pub fn dyn_compatibility_violations(
132    db: &dyn HirDatabase,
133    trait_: TraitId,
134) -> Option<DynCompatibilityViolations> {
135    let mut violations = Vec::new();
136    for &super_trait in &SupertraitsInfo::query(db, trait_).direct_supertraits {
137        if let Some(supertrait_violations) = dyn_compatibility_violations(db, super_trait) {
138            violations.push(DynCompatibilityViolation::HasNonCompatibleSuperTrait(
139                super_trait,
140                supertrait_violations.clone(),
141            ));
142        }
143    }
144
145    let krate = trait_.krate(db);
146    let interner = DbInterner::new_with(db, krate);
147    let mut features = LazyFeatures { krate, features: None };
148    dyn_compatibility_violations_for_trait(interner, &mut features, trait_, &mut violations);
149
150    if violations.is_empty() {
151        None
152    } else {
153        Some(ThinArc::from_header_and_iter((), violations.into_iter()))
154    }
155}
156
157#[instrument(level = "debug", skip(interner, features))]
158fn dyn_compatibility_violations_for_trait<'db>(
159    interner: DbInterner<'db>,
160    features: &mut LazyFeatures<'db>,
161    trait_def_id: TraitId,
162    violations: &mut Vec<DynCompatibilityViolation>,
163) {
164    let db = interner.db;
165
166    // Check assoc items for violations.
167    let trait_items = trait_def_id.trait_items(db);
168    for &(_, item) in &trait_items.items {
169        dyn_compatibility_violations_for_assoc_item(
170            interner,
171            features,
172            trait_def_id,
173            item,
174            violations,
175        );
176    }
177
178    // Check the trait itself.
179    if trait_has_sized_self(db, trait_def_id) {
180        violations.push(DynCompatibilityViolation::SizedSelf);
181    } else if AttrFlags::query(db, trait_def_id.into())
182        .contains(AttrFlags::RUSTC_DYN_INCOMPATIBLE_TRAIT)
183    {
184        violations.push(DynCompatibilityViolation::ExplicitlyDynIncompatible);
185    }
186
187    if clauses_reference_self(interner, trait_def_id) {
188        violations.push(DynCompatibilityViolation::SupertraitSelf);
189    }
190    if bounds_reference_self(interner, trait_def_id, trait_items) {
191        violations.push(DynCompatibilityViolation::SupertraitSelf);
192    }
193    if super_clauses_have_non_lifetime_binders(interner, trait_def_id) {
194        violations.push(DynCompatibilityViolation::SupertraitNonLifetimeBinder);
195    }
196    if super_clauses_are_unconditionally_const(interner, trait_def_id) {
197        violations.push(DynCompatibilityViolation::SupertraitConst);
198    }
199}
200
201fn clauses_reference_self(interner: DbInterner<'_>, trait_def_id: TraitId) -> bool {
202    let trait_ref = Binder::dummy(TraitRef::identity(interner, trait_def_id.into()));
203    let clauses = GenericPredicates::query_own(interner.db, trait_def_id.into());
204    clauses.skip_binder().map(|clause| clause.instantiate_supertrait(interner, trait_ref)).any(
205        |clause| {
206            // Super clauses cannot allow self projections, since they're
207            // impossible to make into existential bounds without eager resolution
208            // or something.
209            // e.g. `trait A: B<Item = Self::Assoc>`.
210            predicate_references_self(interner, trait_def_id, clause, AllowSelfProjections::No)
211        },
212    )
213}
214
215fn bounds_reference_self(
216    interner: DbInterner<'_>,
217    trait_def_id: TraitId,
218    trait_items: &TraitItems,
219) -> bool {
220    trait_items
221        .items
222        .iter()
223        // We're only looking at associated type bounds
224        .filter_map(|&(_, item)| match item {
225            AssocItemId::TypeAliasId(it) => Some(it),
226            AssocItemId::FunctionId(_) | AssocItemId::ConstId(_) => None,
227        })
228        // Ignore GATs with `Self: Sized`
229        .filter(|&item| !generics_require_sized_self(interner.db, item.into()))
230        .flat_map(|item| {
231            interner
232                .db
233                .type_alias_bounds(item)
234                .iter_identity_copied()
235                .map(Unnormalized::skip_norm_wip)
236        })
237        .any(|clause| {
238            // Item bounds *can* have self projections, since they never get
239            // their self type erased.
240            predicate_references_self(interner, trait_def_id, clause, AllowSelfProjections::Yes)
241        })
242}
243
244fn predicate_references_self<'db>(
245    interner: DbInterner<'db>,
246    trait_def_id: TraitId,
247    predicate: Clause<'db>,
248    allow_self_projections: AllowSelfProjections,
249) -> bool {
250    match predicate.kind().skip_binder() {
251        ClauseKind::Trait(ref data) => {
252            // In the case of a trait predicate, we can skip the "self" type.
253            data.trait_ref.args[1..].iter().any(|&arg| {
254                contains_illegal_self_type_reference(
255                    interner,
256                    trait_def_id,
257                    arg,
258                    allow_self_projections,
259                )
260            })
261        }
262        ClauseKind::Projection(ref data) => {
263            // And similarly for projections. This should be redundant with
264            // the previous check because any projection should have a
265            // matching `Trait` predicate with the same inputs, but we do
266            // the check to be safe.
267            //
268            // It's also won't be redundant if we allow type-generic associated
269            // types for trait objects.
270            //
271            // Note that we *do* allow projection *outputs* to contain
272            // `Self` (i.e., `trait Foo: Bar<Output=Self::Result> { type Result; }`),
273            // we just require the user to specify *both* outputs
274            // in the object type (i.e., `dyn Foo<Output=(), Result=()>`).
275            //
276            // This is ALT2 in issue #56288, see that for discussion of the
277            // possible alternatives.
278            data.projection_term.args[1..].iter().any(|&arg| {
279                contains_illegal_self_type_reference(
280                    interner,
281                    trait_def_id,
282                    arg,
283                    allow_self_projections,
284                )
285            })
286        }
287        ClauseKind::ConstArgHasType(_ct, ty) => {
288            contains_illegal_self_type_reference(interner, trait_def_id, ty, allow_self_projections)
289        }
290
291        ClauseKind::WellFormed(..)
292        | ClauseKind::TypeOutlives(..)
293        | ClauseKind::RegionOutlives(..)
294        | ClauseKind::HostEffect(..)
295        | ClauseKind::UnstableFeature(_) => false,
296
297        // FIXME(generic_const_exprs): this can mention `Self`
298        ClauseKind::ConstEvaluatable(..) => false,
299    }
300}
301
302fn super_clauses_have_non_lifetime_binders(
303    interner: DbInterner<'_>,
304    trait_def_id: TraitId,
305) -> bool {
306    interner
307        .explicit_super_predicates_of(trait_def_id.into())
308        .iter_identity()
309        .map(Unnormalized::skip_norm_wip)
310        .any(|(clause, _)| clause.has_non_region_bound_vars())
311}
312
313/// Checks for `const Trait` supertraits. We're okay with `[const] Trait`,
314/// supertraits since for a non-const instantiation of that trait, the
315/// conditionally-const supertrait is also not required to be const.
316fn super_clauses_are_unconditionally_const(
317    interner: DbInterner<'_>,
318    trait_def_id: TraitId,
319) -> bool {
320    interner
321        .explicit_super_predicates_of(trait_def_id.into())
322        .iter_identity()
323        .map(Unnormalized::skip_norm_wip)
324        .any(|(clause, _)| matches!(clause.kind().skip_binder(), ClauseKind::HostEffect(_)))
325}
326
327fn trait_has_sized_self(db: &dyn HirDatabase, trait_def_id: TraitId) -> bool {
328    generics_require_sized_self(db, trait_def_id.into())
329}
330
331#[salsa::tracked(returns(copy))]
332pub fn generics_require_sized_self(db: &dyn HirDatabase, def_id: GenericDefId) -> bool {
333    let interner = DbInterner::new_with(db, def_id.krate(db));
334    let Some(sized_def_id) = interner.lang_items().Sized else {
335        return false; /* No Sized trait, can't require it! */
336    };
337
338    // Search for a clause like `Self: Sized` amongst the trait bounds.
339    let clauses = GenericPredicates::query_own_explicit(db, def_id)
340        .iter_identity()
341        .map(Unnormalized::skip_norm_wip);
342    elaborate(interner, clauses).any(|clause| match clause.kind().skip_binder() {
343        ClauseKind::Trait(ref trait_pred) => {
344            trait_pred.def_id().0 == sized_def_id && trait_pred.self_ty().is_param(0)
345        }
346        ClauseKind::RegionOutlives(_)
347        | ClauseKind::TypeOutlives(_)
348        | ClauseKind::Projection(_)
349        | ClauseKind::ConstArgHasType(_, _)
350        | ClauseKind::WellFormed(_)
351        | ClauseKind::ConstEvaluatable(_)
352        | ClauseKind::UnstableFeature(_)
353        | ClauseKind::HostEffect(..) => false,
354    })
355}
356
357#[instrument(level = "debug", skip(interner, features))]
358fn dyn_compatibility_violations_for_assoc_item<'db>(
359    interner: DbInterner<'db>,
360    features: &mut LazyFeatures<'db>,
361    trait_def_id: TraitId,
362    item: AssocItemId,
363    violations: &mut Vec<DynCompatibilityViolation>,
364) {
365    let db = interner.db;
366
367    // FIXME: `final` assoc functions don't prevent a trait from being dyn-compatible
368    // if db.defaultness(item.def_id).is_final() {
369    //     return;
370    // }
371
372    // Any item that has a `Self: Sized` requisite is otherwise exempt from the regulations.
373    if generics_require_sized_self(db, item.into()) {
374        return;
375    }
376
377    match item {
378        AssocItemId::ConstId(item) => {
379            // We will permit type associated consts if they are explicitly mentioned in the
380            // trait object type. We can't check this here, as here we only check if it is
381            // guaranteed to not be possible.
382
383            let mut push_violation =
384                |violation| violations.push(DynCompatibilityViolation::AssocConst(item, violation));
385
386            let features = features.get(db);
387            if features.gca_min_const_items {
388                if !GenericParams::of(db, item.into()).is_empty() {
389                    push_violation(AssocConstViolation::Generic);
390                } else if !AttrFlags::query(db, item.into()).contains(AttrFlags::RUSTC_ALWAYS_GCA)
391                    && !features.gca_const_items
392                {
393                    push_violation(AssocConstViolation::NonType);
394                }
395
396                let ty = Binder::dummy(
397                    db.value_ty(item.into()).unwrap().instantiate_identity().skip_norm_wip(),
398                );
399                if contains_illegal_self_type_reference(
400                    interner,
401                    trait_def_id,
402                    ty,
403                    AllowSelfProjections::Yes,
404                ) {
405                    push_violation(AssocConstViolation::TypeReferencesSelf);
406                }
407            } else {
408                push_violation(AssocConstViolation::FeatureNotEnabled);
409            }
410        }
411        AssocItemId::FunctionId(item) => {
412            virtual_call_violations_for_method(interner, trait_def_id, item, violations)
413        }
414        AssocItemId::TypeAliasId(item) => {
415            if !GenericParams::of(db, item.into()).is_empty() {
416                violations.push(DynCompatibilityViolation::GenericAssocTy(item));
417            }
418            // We will permit associated types if they are explicitly mentioned in the trait
419            // object type. We can't check this here, as here we only check if it is
420            // guaranteed to not be possible.
421        }
422    }
423}
424
425/// Returns `Some(_)` if this method cannot be called on a trait
426/// object; this does not necessarily imply that the enclosing trait
427/// is dyn-incompatible, because the method might have a where clause
428/// `Self: Sized`.
429fn virtual_call_violations_for_method<'db>(
430    interner: DbInterner<'db>,
431    trait_def_id: TraitId,
432    method: FunctionId,
433    violations: &mut Vec<DynCompatibilityViolation>,
434) {
435    let db = interner.db;
436    let mut push_violation =
437        |violation| violations.push(DynCompatibilityViolation::Method(method, violation));
438
439    let sig = db.callable_item_signature(method.into()).instantiate_identity().skip_norm_wip();
440    let data = FunctionSignature::of(db, method);
441
442    // The method's first parameter must be named `self`
443    if !data.has_self_param() {
444        push_violation(MethodViolation::StaticMethod);
445        // Not having `self` parameter messes up the later checks,
446        // so we need to return instead of pushing
447        return;
448    }
449
450    for &input_ty in sig.skip_binder().inputs().iter().skip(1) {
451        if contains_illegal_self_type_reference(
452            interner,
453            trait_def_id,
454            sig.rebind(input_ty),
455            AllowSelfProjections::Yes,
456        ) {
457            push_violation(MethodViolation::ReferencesSelfInput);
458        }
459    }
460    if contains_illegal_self_type_reference(
461        interner,
462        trait_def_id,
463        sig.output(),
464        AllowSelfProjections::Yes,
465    ) {
466        push_violation(MethodViolation::ReferencesSelfOutput);
467    }
468    if let Some(error) = contains_illegal_impl_trait_in_trait(interner, method, data, sig.output())
469    {
470        push_violation(error);
471    }
472    if sig.skip_binder().c_variadic() {
473        push_violation(MethodViolation::CVariadic);
474    }
475
476    // We can't monomorphize things like `fn foo<A>(...)`.
477    if data.generic_params.len_type_or_consts() != 0 {
478        push_violation(MethodViolation::Generic);
479    }
480
481    let receiver_ty = interner.liberate_late_bound_regions(method.into(), sig.input(0));
482
483    let clauses = GenericPredicates::query(db, method.into());
484
485    // `self: Self` can't be dispatched on.
486    // However, this is considered dyn compatible. We allow it as a special case here.
487    // FIXME(mikeyhew) get rid of this `if` statement once `receiver_is_dispatchable` allows
488    // `Receiver: Unsize<Receiver[Self => dyn Trait]>`.
489    if !receiver_ty.is_param(0) {
490        if !receiver_is_dispatchable(interner, trait_def_id, method, receiver_ty, clauses) {
491            push_violation(MethodViolation::UndispatchableReceiver);
492        } else {
493            // We confirm that the `receiver_is_dispatchable` is accurate later,
494            // see `check_receiver_correct`. It should be kept in sync with this code.
495        }
496    }
497
498    // NOTE: This check happens last, because it results in a lint, and not a
499    // hard error.
500    if clauses.own_predicates().skip_binder().any(|clause| {
501        // dyn Trait is okay:
502        //
503        //     trait Trait {
504        //         fn f(&self) where Self: 'static;
505        //     }
506        //
507        // because a trait object can't claim to live longer than the concrete
508        // type. If the lifetime bound holds on dyn Trait then it's guaranteed
509        // to hold as well on the concrete type.
510        if clause.as_type_outlives_clause().is_some() {
511            return false;
512        }
513
514        // dyn Trait is okay:
515        //
516        //     auto trait AutoTrait {}
517        //
518        //     trait Trait {
519        //         fn f(&self) where Self: AutoTrait;
520        //     }
521        //
522        // because `impl AutoTrait for dyn Trait` is disallowed by coherence.
523        // Traits with a default impl are implemented for a trait object if and
524        // only if the autotrait is one of the trait object's trait bounds, like
525        // in `dyn Trait + AutoTrait`. This guarantees that trait objects only
526        // implement auto traits if the underlying type does as well.
527        if let ClauseKind::Trait(TraitPredicate {
528            trait_ref: pred_trait_ref,
529            polarity: PredicatePolarity::Positive,
530        }) = clause.kind().skip_binder()
531            && pred_trait_ref.self_ty().is_param(0)
532            && TraitSignature::of(db, pred_trait_ref.def_id.0).flags.contains(TraitFlags::AUTO)
533        {
534            return false;
535        }
536
537        contains_illegal_self_type_reference(
538            interner,
539            trait_def_id,
540            clause,
541            AllowSelfProjections::Yes,
542        )
543    }) {
544        push_violation(MethodViolation::WhereClauseReferencesSelf);
545    }
546}
547
548/// Performs a type instantiation to produce the version of `receiver_ty` when `Self = self_ty`.
549/// For example, for `receiver_ty = Rc<Self>` and `self_ty = Foo`, returns `Rc<Foo>`.
550fn receiver_for_self_ty<'db>(
551    interner: DbInterner<'db>,
552    receiver_ty: Ty<'db>,
553    self_ty: Ty<'db>,
554    method_def_id: FunctionId,
555) -> Ty<'db> {
556    debug!("receiver_for_self_ty({:?}, {:?}, {:?})", receiver_ty, self_ty, method_def_id);
557    let args = GenericArgs::for_item(interner, method_def_id.into(), |index, param, _, _| {
558        if index == 0 { self_ty.into() } else { mk_param(interner, index, param) }
559    });
560
561    let result = EarlyBinder::bind(receiver_ty).instantiate(interner, args).skip_norm_wip();
562    debug!(
563        "receiver_for_self_ty({:?}, {:?}, {:?}) = {:?}",
564        receiver_ty, self_ty, method_def_id, result
565    );
566    result
567}
568
569/// Checks the method's receiver (the `self` argument) can be dispatched on when `Self` is a
570/// trait object. We require that `DispatchableFromDyn` be implemented for the receiver type
571/// in the following way:
572/// - let `Receiver` be the type of the `self` argument, i.e `Self`, `&Self`, `Rc<Self>`,
573/// - require the following bound:
574///
575///   ```ignore (not-rust)
576///   Receiver[Self => T]: DispatchFromDyn<Receiver[Self => dyn Trait]>
577///   ```
578///
579///   where `Foo[X => Y]` means "the same type as `Foo`, but with `X` replaced with `Y`"
580///   (instantiation notation).
581///
582/// Some examples of receiver types and their required obligation:
583/// - `&'a mut self` requires `&'a mut Self: DispatchFromDyn<&'a mut dyn Trait>`,
584/// - `self: Rc<Self>` requires `Rc<Self>: DispatchFromDyn<Rc<dyn Trait>>`,
585/// - `self: Pin<Box<Self>>` requires `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<dyn Trait>>>`.
586///
587/// The only case where the receiver is not dispatchable, but is still a valid receiver
588/// type (just not dyn compatible), is when there is more than one level of pointer indirection.
589/// E.g., `self: &&Self`, `self: &Rc<Self>`, `self: Box<Box<Self>>`. In these cases, there
590/// is no way, or at least no inexpensive way, to coerce the receiver from the version where
591/// `Self = dyn Trait` to the version where `Self = T`, where `T` is the unknown erased type
592/// contained by the trait object, because the object that needs to be coerced is behind
593/// a pointer.
594///
595/// If lowering already produced an error in the receiver type, we conservatively treat it as
596/// undispatchable instead of asking the solver.
597///
598/// In practice, we cannot use `dyn Trait` explicitly in the obligation because it would result in
599/// a new check that `Trait` is dyn-compatible, creating a cycle.
600/// Instead, we emulate a placeholder by introducing a new type parameter `U` such that
601/// `Self: Unsize<U>` and `U: Trait + MetaSized`, and use `U` in place of `dyn Trait`.
602///
603/// Written as a chalk-style query:
604/// ```ignore (not-rust)
605/// forall (U: Trait + MetaSized) {
606///     if (Self: Unsize<U>) {
607///         Receiver: DispatchFromDyn<Receiver[Self => U]>
608///     }
609/// }
610/// ```
611/// for `self: &'a mut Self`, this means `&'a mut Self: DispatchFromDyn<&'a mut U>`
612/// for `self: Rc<Self>`, this means `Rc<Self>: DispatchFromDyn<Rc<U>>`
613/// for `self: Pin<Box<Self>>`, this means `Pin<Box<Self>>: DispatchFromDyn<Pin<Box<U>>>`
614//
615// FIXME(mikeyhew) when unsized receivers are implemented as part of unsized rvalues, add this
616// fallback query: `Receiver: Unsize<Receiver[Self => U]>` to support receivers like
617// `self: Wrapper<Self>`.
618fn receiver_is_dispatchable<'db>(
619    interner: DbInterner<'db>,
620    trait_def_id: TraitId,
621    method: FunctionId,
622    receiver_ty: Ty<'db>,
623    clauses: &GenericPredicates,
624) -> bool {
625    debug!("receiver_is_dispatchable: method = {:?}, receiver_ty = {:?}", method, receiver_ty);
626
627    let lang_items = interner.lang_items();
628    let (Some(unsize_did), Some(dispatch_from_dyn_did)) =
629        (lang_items.Unsize, lang_items.DispatchFromDyn)
630    else {
631        debug!("receiver_is_dispatchable: Missing `Unsize` or `DispatchFromDyn` traits");
632        return true;
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 self_param_id = TypeParamId::from_unchecked(TypeOrConstParamId {
638        parent: trait_def_id.into(),
639        local_id: LocalTypeOrConstParamId::from_raw(la_arena::RawIdx::from_u32(0)),
640    });
641    let self_param_ty =
642        Ty::new(interner, rustc_type_ir::TyKind::Param(ParamTy { index: 0, id: self_param_id }));
643    // FIXME: That seems problematic to fake a generic param like that?
644    let unsized_self_ty = Ty::new_param(interner, self_param_id, u32::MAX);
645
646    // `Receiver[Self => U]`
647    let unsized_receiver_ty = receiver_for_self_ty(interner, receiver_ty, unsized_self_ty, method);
648
649    // create a modified param env, with `Self: Unsize<U>` and `U: Trait` (and all of
650    // its supertraits) added to caller bounds. `U: MetaSized` is already implied here.
651    let param_env = {
652        // N.B. We generally want to emulate the construction of the `unnormalized_param_env`
653        // in the param-env query here. The fact that we don't just start with the clauses
654        // in the param-env of the method is because those are already normalized, and mixing
655        // normalized and unnormalized copies of predicates in `normalize_param_env_or_error`
656        // will cause ambiguity that the user can't really avoid.
657        //
658        // We leave out certain complexities of the param-env query here. Specifically, we:
659        // 1. Do not add `[const]` bounds since there are no `dyn const Trait`s.
660        // 2. Do not add RPITIT self projection bounds for defaulted methods, since we
661        //    are not constructing a param-env for "inside" of the body of the defaulted
662        //    method, so we don't really care about projecting to a specific RPIT type,
663        //    and because RPITITs are not dyn compatible (yet).
664        let mut clauses: Vec<_> =
665            clauses.all_predicates().iter_identity().map(Unnormalized::skip_norm_wip).collect();
666
667        // Self: Unsize<U>
668        let unsize_predicate =
669            TraitRef::new(interner, unsize_did.into(), [self_param_ty, unsized_self_ty]);
670        clauses.push(unsize_predicate.upcast(interner));
671
672        // U: Trait<Arg1, ..., ArgN>
673        let args = GenericArgs::for_item(interner, trait_def_id.into(), |index, param, _, _| {
674            if index == 0 { unsized_self_ty.into() } else { mk_param(interner, index, param) }
675        });
676        let trait_predicate = TraitRef::new_from_args(interner, trait_def_id.into(), args);
677        clauses.push(trait_predicate.upcast(interner));
678
679        let meta_sized_predicate = {
680            let Some(meta_sized_did) = lang_items.MetaSized else { return true };
681            TraitRef::new(interner, meta_sized_did.into(), [unsized_self_ty])
682        };
683        clauses.push(meta_sized_predicate.upcast(interner));
684
685        // FIXME: We need to do something with normalization here, but I'm not sure what the status of ParamEnv normalization
686        // with the new solver is. Revisit when things are more clear.
687        // normalize_param_env_or_error(
688        //     db,
689        //     ty::ParamEnv::new(db.mk_clauses(&clauses)),
690        //     ObligationCause::dummy_with_span(db.def_span(method.def_id)),
691        // )
692        ParamEnv { clauses: Clauses::new_from_slice(&clauses) }
693    };
694
695    // Receiver: DispatchFromDyn<Receiver[Self => U]>
696    let obligation = {
697        let predicate = TraitRef::new(
698            interner,
699            dispatch_from_dyn_did.into(),
700            [receiver_ty, unsized_receiver_ty],
701        );
702
703        Obligation::new(interner, ObligationCause::dummy(), param_env, predicate)
704    };
705
706    let infcx = interner.infer_ctxt().build(TypingMode::non_body_analysis());
707    // the receiver is dispatchable iff the obligation holds
708    infcx.predicate_must_hold_modulo_regions(&obligation)
709}
710
711#[derive(Copy, Clone)]
712enum AllowSelfProjections {
713    Yes,
714    No,
715}
716
717/// Check if the given value contains illegal `Self` references.
718///
719/// This is somewhat subtle. In general, we want to forbid references to `Self` in the
720/// argument and return types, since the value of `Self` is erased.
721///
722/// However, there is one exception: It is ok to reference `Self` in order to access an
723/// associated type of the current trait, since we retain the value of those associated
724/// types in the trait object type itself.
725///
726/// The same thing holds for associated consts under feature `min_generic_const_args`.
727///
728/// ```rust,ignore (example)
729/// trait SuperTrait {
730///     type X;
731/// }
732///
733/// trait Trait : SuperTrait {
734///     type Y;
735///     fn foo(&self, x: Self) // bad
736///     fn foo(&self) -> Self // bad
737///     fn foo(&self) -> Option<Self> // bad
738///     fn foo(&self) -> Self::Y // OK, desugars to next example
739///     fn foo(&self) -> <Self as Trait>::Y // OK
740///     fn foo(&self) -> Self::X // OK, desugars to next example
741///     fn foo(&self) -> <Self as SuperTrait>::X // OK
742/// }
743/// ```
744///
745/// However, it is not as simple as allowing `Self` in a projected
746/// type, because there are illegal ways to use `Self` as well:
747///
748/// ```rust,ignore (example)
749/// trait Trait : SuperTrait {
750///     ...
751///     fn foo(&self) -> <Self as SomeOtherTrait>::X;
752/// }
753/// ```
754///
755/// Here we will not have the type of `X` recorded in the
756/// object type, and we cannot resolve `Self as SomeOtherTrait`
757/// without knowing what `Self` is.
758fn contains_illegal_self_type_reference<'db, T: TypeVisitable<DbInterner<'db>>>(
759    interner: DbInterner<'db>,
760    trait_def_id: TraitId,
761    value: T,
762    allow_self_projections: AllowSelfProjections,
763) -> bool {
764    value
765        .visit_with(&mut IllegalSelfTypeVisitor {
766            interner,
767            trait_def_id,
768            supertraits: None,
769            allow_self_projections,
770            types: default_types(),
771        })
772        .is_break()
773}
774
775struct IllegalSelfTypeVisitor<'db> {
776    interner: DbInterner<'db>,
777    trait_def_id: TraitId,
778    supertraits: Option<Vec<TraitRef<'db>>>,
779    allow_self_projections: AllowSelfProjections,
780    types: &'db DefaultAny<'db>,
781}
782
783impl<'db> IllegalSelfTypeVisitor<'db> {
784    fn is_supertrait_of_current_trait(&mut self, trait_ref: TraitRef<'db>) -> bool {
785        let interner = self.interner;
786        // Compute supertraits of current trait lazily.
787        let supertraits = self.supertraits.get_or_insert_with(|| {
788            elaborate::supertraits(
789                interner,
790                Binder::dummy(TraitRef::identity(interner, self.trait_def_id.into())),
791            )
792            .map(|trait_ref| {
793                interner.erase_and_anonymize_regions(
794                    interner.instantiate_bound_regions_with_erased(trait_ref),
795                )
796            })
797            .collect()
798        });
799
800        // Determine whether the given trait ref is in fact a supertrait of the current trait.
801        // In that case, any derived projections are legal, because the term will be specified
802        // in the trait object type.
803        // Note that we can just use direct equality here because all of these types are part of
804        // the formal parameter listing, and hence there should be no inference variables.
805        let trait_ref = trait_ref.fold_with(&mut EraseEscapingBoundRegions {
806            interner: self.interner,
807            binder: rustc_type_ir::INNERMOST,
808            types: self.types,
809        });
810        supertraits.contains(&trait_ref)
811    }
812}
813
814impl<'db> TypeVisitor<DbInterner<'db>> for IllegalSelfTypeVisitor<'db> {
815    type Result = ControlFlow<()>;
816
817    fn visit_ty(&mut self, ty: Ty<'db>) -> Self::Result {
818        match ty.kind() {
819            TyKind::Param(_) => {
820                if ty.is_param(GenericParams::SELF_PARAM_ID_IN_SELF.into_raw().into_u32()) {
821                    ControlFlow::Break(())
822                } else {
823                    ControlFlow::Continue(())
824                }
825            }
826            // FIXME: Once we implement RPITIT.
827            // TyKind::Alias(_, AliasTy { kind: AliasTyKind::Projection { def_id }, .. })
828            //     if self.db.is_impl_trait_in_trait(*def_id) =>
829            // {
830            //     // We'll deny these later in their own pass
831            //     ControlFlow::Continue(())
832            // }
833            TyKind::Alias(proj @ AliasTy { kind: AliasTyKind::Projection { .. }, .. }) => {
834                match self.allow_self_projections {
835                    AllowSelfProjections::Yes => {
836                        // Only walk contained types if the parent trait is not a supertrait.
837                        if self.is_supertrait_of_current_trait(proj.trait_ref(self.interner)) {
838                            ControlFlow::Continue(())
839                        } else {
840                            ty.super_visit_with(self)
841                        }
842                    }
843                    AllowSelfProjections::No => ty.super_visit_with(self),
844                }
845            }
846            _ => ty.super_visit_with(self),
847        }
848    }
849
850    // FIXME: Should implement this once we sync rustc_type_ir enough and potentially implement GCA.
851    // fn visit_const(&mut self, ct: Const<'db>) -> Self::Result {
852    //     let ct = self.db.expand_abstract_consts(ct);
853
854    //     match ct.kind() {
855    //         ty::ConstKind::Alias(
856    //             _,
857    //             ty::AliasConst { kind: ty::AliasConstKind::Projection { def_id }, args, .. },
858    //         ) if self.db.features().min_generic_const_args() => {
859    //             match self.allow_self_projections {
860    //                 AllowSelfProjections::Yes => {
861    //                     let trait_def_id = self.db.parent(def_id);
862    //                     let trait_ref = TraitRef::from_assoc(self.interner, trait_def_id, args);
863
864    //                     // Only walk contained consts if the parent trait is not a supertrait.
865    //                     if self.is_supertrait_of_current_trait(trait_ref) {
866    //                         ControlFlow::Continue(())
867    //                     } else {
868    //                         ct.super_visit_with(self)
869    //                     }
870    //                 }
871    //                 AllowSelfProjections::No => ct.super_visit_with(self),
872    //             }
873    //         }
874    //         _ => ct.super_visit_with(self),
875    //     }
876    // }
877}
878
879struct EraseEscapingBoundRegions<'db> {
880    interner: DbInterner<'db>,
881    binder: DebruijnIndex,
882    types: &'db DefaultAny<'db>,
883}
884
885impl<'db> TypeFolder<DbInterner<'db>> for EraseEscapingBoundRegions<'db> {
886    fn cx(&self) -> DbInterner<'db> {
887        self.interner
888    }
889
890    fn fold_binder<T>(&mut self, t: Binder<'db, T>) -> Binder<'db, T>
891    where
892        T: TypeFoldable<DbInterner<'db>>,
893    {
894        self.binder.shift_in(1);
895        let result = t.super_fold_with(self);
896        self.binder.shift_out(1);
897        result
898    }
899
900    fn fold_region(&mut self, r: Region<'db>) -> Region<'db> {
901        if let RegionKind::ReBound(BoundVarIndexKind::Bound(debruijn), _) = r.kind()
902            && debruijn < self.binder
903        {
904            r
905        } else {
906            self.types.regions.erased
907        }
908    }
909}
910
911fn contains_illegal_impl_trait_in_trait<'db>(
912    interner: DbInterner<'db>,
913    fn_def_id: FunctionId,
914    data: &FunctionSignature,
915    ty: Binder<'db, Ty<'db>>,
916) -> Option<MethodViolation> {
917    if !ty.has_aliases() {
918        return None;
919    }
920
921    let ty = interner.liberate_late_bound_regions(fn_def_id.into(), ty);
922
923    if data.is_async() {
924        // Rendering the error as a separate `async-specific` message is better.
925        Some(MethodViolation::AsyncFn)
926    } else {
927        ty.visit_with(&mut IllegalRpititVisitor { db: interner.db }).break_value()
928    }
929}
930
931struct IllegalRpititVisitor<'db> {
932    db: &'db dyn HirDatabase,
933}
934
935impl<'db> TypeVisitor<DbInterner<'db>> for IllegalRpititVisitor<'db> {
936    type Result = ControlFlow<MethodViolation>;
937
938    fn visit_ty(&mut self, ty: Ty<'db>) -> Self::Result {
939        if let TyKind::Alias(AliasTy { kind: AliasTyKind::Opaque { def_id }, .. }) = ty.kind()
940            && matches!(def_id.0.loc(self.db), ImplTraitId::ReturnTypeImplTrait(..))
941        {
942            ControlFlow::Break(MethodViolation::ReferencesImplTraitInTrait)
943        } else {
944            ty.super_visit_with(self)
945        }
946    }
947}