rustc_middle/ty/
return_position_impl_trait_in_trait.rs

1use rustc_hir::def_id::DefId;
2
3use crate::ty::{self, ExistentialPredicateStableCmpExt, TyCtxt};
4
5impl<'tcx> TyCtxt<'tcx> {
6    /// Given a `def_id` of a trait or impl method, compute whether that method needs to
7    /// have an RPITIT shim applied to it for it to be dyn compatible. If so, return the
8    /// `def_id` of the RPITIT, and also the args of trait method that returns the RPITIT.
9    ///
10    /// NOTE that these args are not, in general, the same as than the RPITIT's args. They
11    /// are a subset of those args,  since they do not include the late-bound lifetimes of
12    /// the RPITIT. Depending on the context, these will need to be dealt with in different
13    /// ways -- in codegen, it's okay to fill them with ReErased.
14    pub fn return_position_impl_trait_in_trait_shim_data(
15        self,
16        def_id: DefId,
17    ) -> Option<(DefId, ty::EarlyBinder<'tcx, ty::GenericArgsRef<'tcx>>)> {
18        let assoc_item = self.opt_associated_item(def_id)?;
19
20        let (trait_item_def_id, opt_impl_def_id) = match assoc_item.container {
21            ty::AssocItemContainer::Impl => {
22                (assoc_item.trait_item_def_id?, Some(self.parent(def_id)))
23            }
24            ty::AssocItemContainer::Trait => (def_id, None),
25        };
26
27        let sig = self.fn_sig(trait_item_def_id);
28
29        // Check if the trait returns an RPITIT.
30        let ty::Alias(ty::Projection, ty::AliasTy { def_id, .. }) =
31            *sig.skip_binder().skip_binder().output().kind()
32        else {
33            return None;
34        };
35        if !self.is_impl_trait_in_trait(def_id) {
36            return None;
37        }
38
39        let args = if let Some(impl_def_id) = opt_impl_def_id {
40            // Rebase the args from the RPITIT onto the impl trait ref, so we can later
41            // substitute them with the method args of the *impl* method, since that's
42            // the instance we're building a vtable shim for.
43            ty::GenericArgs::identity_for_item(self, trait_item_def_id).rebase_onto(
44                self,
45                self.parent(trait_item_def_id),
46                self.impl_trait_ref(impl_def_id)
47                    .expect("expected impl trait ref from parent of impl item")
48                    .instantiate_identity()
49                    .args,
50            )
51        } else {
52            // This is when we have a default trait implementation.
53            ty::GenericArgs::identity_for_item(self, trait_item_def_id)
54        };
55
56        Some((def_id, ty::EarlyBinder::bind(args)))
57    }
58
59    /// Given a `DefId` of an RPITIT and its args, return the existential predicates
60    /// that corresponds to the RPITIT's bounds with the self type erased.
61    pub fn item_bounds_to_existential_predicates(
62        self,
63        def_id: DefId,
64        args: ty::GenericArgsRef<'tcx>,
65    ) -> &'tcx ty::List<ty::PolyExistentialPredicate<'tcx>> {
66        let mut bounds: Vec<_> = self
67            .item_self_bounds(def_id)
68            .iter_instantiated(self, args)
69            .filter_map(|clause| {
70                clause
71                    .kind()
72                    .map_bound(|clause| match clause {
73                        ty::ClauseKind::Trait(trait_pred) => Some(ty::ExistentialPredicate::Trait(
74                            ty::ExistentialTraitRef::erase_self_ty(self, trait_pred.trait_ref),
75                        )),
76                        ty::ClauseKind::Projection(projection_pred) => {
77                            Some(ty::ExistentialPredicate::Projection(
78                                ty::ExistentialProjection::erase_self_ty(self, projection_pred),
79                            ))
80                        }
81                        ty::ClauseKind::TypeOutlives(_) => {
82                            // Type outlives bounds don't really turn into anything,
83                            // since we must use an intersection region for the `dyn*`'s
84                            // region anyways.
85                            None
86                        }
87                        _ => unreachable!("unexpected clause in item bounds: {clause:?}"),
88                    })
89                    .transpose()
90            })
91            .collect();
92        bounds.sort_by(|a, b| a.skip_binder().stable_cmp(self, &b.skip_binder()));
93        self.mk_poly_existential_predicates(&bounds)
94    }
95}