rustc_ty_utils/
implied_bounds.rs

1use std::iter;
2
3use rustc_data_structures::fx::FxHashMap;
4use rustc_hir as hir;
5use rustc_hir::def::DefKind;
6use rustc_hir::def_id::LocalDefId;
7use rustc_middle::bug;
8use rustc_middle::query::Providers;
9use rustc_middle::ty::{self, Ty, TyCtxt, fold_regions};
10use rustc_span::Span;
11
12pub(crate) fn provide(providers: &mut Providers) {
13    *providers = Providers {
14        assumed_wf_types,
15        assumed_wf_types_for_rpitit: |tcx, def_id| {
16            assert!(tcx.is_impl_trait_in_trait(def_id.to_def_id()));
17            tcx.assumed_wf_types(def_id)
18        },
19        ..*providers
20    };
21}
22
23fn assumed_wf_types<'tcx>(tcx: TyCtxt<'tcx>, def_id: LocalDefId) -> &'tcx [(Ty<'tcx>, Span)] {
24    match tcx.def_kind(def_id) {
25        DefKind::Fn => {
26            let sig = tcx.fn_sig(def_id).instantiate_identity();
27            let liberated_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
28            tcx.arena.alloc_from_iter(itertools::zip_eq(
29                liberated_sig.inputs_and_output,
30                fn_sig_spans(tcx, def_id),
31            ))
32        }
33        DefKind::AssocFn => {
34            let sig = tcx.fn_sig(def_id).instantiate_identity();
35            let liberated_sig = tcx.liberate_late_bound_regions(def_id.to_def_id(), sig);
36            let mut assumed_wf_types: Vec<_> =
37                tcx.assumed_wf_types(tcx.local_parent(def_id)).into();
38            assumed_wf_types.extend(itertools::zip_eq(
39                liberated_sig.inputs_and_output,
40                fn_sig_spans(tcx, def_id),
41            ));
42            tcx.arena.alloc_slice(&assumed_wf_types)
43        }
44        DefKind::Impl { .. } => {
45            // Trait arguments and the self type for trait impls or only the self type for
46            // inherent impls.
47            let tys = match tcx.impl_trait_ref(def_id) {
48                Some(trait_ref) => trait_ref.skip_binder().args.types().collect(),
49                None => vec![tcx.type_of(def_id).instantiate_identity()],
50            };
51
52            let mut impl_spans = impl_spans(tcx, def_id);
53            tcx.arena.alloc_from_iter(tys.into_iter().map(|ty| (ty, impl_spans.next().unwrap())))
54        }
55        DefKind::AssocTy if let Some(data) = tcx.opt_rpitit_info(def_id.to_def_id()) => {
56            match data {
57                ty::ImplTraitInTraitData::Trait { fn_def_id, .. } => {
58                    // We need to remap all of the late-bound lifetimes in the assumed wf types
59                    // of the fn (which are represented as ReLateParam) to the early-bound lifetimes
60                    // of the RPITIT (which are represented by ReEarlyParam owned by the opaque).
61                    // Luckily, this is very easy to do because we already have that mapping
62                    // stored in the HIR of this RPITIT.
63                    //
64                    // Side-note: We don't really need to do this remapping for early-bound
65                    // lifetimes because they're already "linked" by the bidirectional outlives
66                    // predicates we insert in the `explicit_predicates_of` query for RPITITs.
67                    let mut mapping = FxHashMap::default();
68                    let generics = tcx.generics_of(def_id);
69
70                    // For each captured opaque lifetime, if it's late-bound (`ReLateParam` in this
71                    // case, since it has been liberated), map it back to the early-bound lifetime of
72                    // the GAT. Since RPITITs also have all of the fn's generics, we slice only
73                    // the end of the list corresponding to the opaque's generics.
74                    for param in &generics.own_params[tcx.generics_of(fn_def_id).own_params.len()..]
75                    {
76                        let orig_lt =
77                            tcx.map_opaque_lifetime_to_parent_lifetime(param.def_id.expect_local());
78                        if matches!(*orig_lt, ty::ReLateParam(..)) {
79                            mapping.insert(
80                                orig_lt,
81                                ty::Region::new_early_param(
82                                    tcx,
83                                    ty::EarlyParamRegion { index: param.index, name: param.name },
84                                ),
85                            );
86                        }
87                    }
88                    // FIXME: This could use a real folder, I guess.
89                    let remapped_wf_tys = fold_regions(
90                        tcx,
91                        tcx.assumed_wf_types(fn_def_id.expect_local()).to_vec(),
92                        |region, _| {
93                            // If `region` is a `ReLateParam` that is captured by the
94                            // opaque, remap it to its corresponding the early-
95                            // bound region.
96                            if let Some(remapped_region) = mapping.get(&region) {
97                                *remapped_region
98                            } else {
99                                region
100                            }
101                        },
102                    );
103                    tcx.arena.alloc_from_iter(remapped_wf_tys)
104                }
105                // Assumed wf types for RPITITs in an impl just inherit (and instantiate)
106                // the assumed wf types of the trait's RPITIT GAT.
107                ty::ImplTraitInTraitData::Impl { .. } => {
108                    let impl_def_id = tcx.local_parent(def_id);
109                    let rpitit_def_id = tcx.associated_item(def_id).trait_item_def_id.unwrap();
110                    let args = ty::GenericArgs::identity_for_item(tcx, def_id).rebase_onto(
111                        tcx,
112                        impl_def_id.to_def_id(),
113                        tcx.impl_trait_ref(impl_def_id).unwrap().instantiate_identity().args,
114                    );
115                    tcx.arena.alloc_from_iter(
116                        ty::EarlyBinder::bind(tcx.assumed_wf_types_for_rpitit(rpitit_def_id))
117                            .iter_instantiated_copied(tcx, args)
118                            .chain(tcx.assumed_wf_types(impl_def_id).into_iter().copied()),
119                    )
120                }
121            }
122        }
123        DefKind::AssocConst | DefKind::AssocTy => tcx.assumed_wf_types(tcx.local_parent(def_id)),
124        DefKind::OpaqueTy => bug!("implied bounds are not defined for opaques"),
125        DefKind::Mod
126        | DefKind::Struct
127        | DefKind::Union
128        | DefKind::Enum
129        | DefKind::Variant
130        | DefKind::Trait
131        | DefKind::TyAlias
132        | DefKind::ForeignTy
133        | DefKind::TraitAlias
134        | DefKind::TyParam
135        | DefKind::Const
136        | DefKind::ConstParam
137        | DefKind::Static { .. }
138        | DefKind::Ctor(_, _)
139        | DefKind::Macro(_)
140        | DefKind::ExternCrate
141        | DefKind::Use
142        | DefKind::ForeignMod
143        | DefKind::AnonConst
144        | DefKind::InlineConst
145        | DefKind::Field
146        | DefKind::LifetimeParam
147        | DefKind::GlobalAsm
148        | DefKind::Closure
149        | DefKind::SyntheticCoroutineBody => ty::List::empty(),
150    }
151}
152
153fn fn_sig_spans(tcx: TyCtxt<'_>, def_id: LocalDefId) -> impl Iterator<Item = Span> {
154    let node = tcx.hir_node_by_def_id(def_id);
155    if let Some(decl) = node.fn_decl() {
156        decl.inputs.iter().map(|ty| ty.span).chain(iter::once(decl.output.span()))
157    } else {
158        bug!("unexpected item for fn {def_id:?}: {node:?}")
159    }
160}
161
162fn impl_spans(tcx: TyCtxt<'_>, def_id: LocalDefId) -> impl Iterator<Item = Span> {
163    let item = tcx.hir_expect_item(def_id);
164    if let hir::ItemKind::Impl(impl_) = item.kind {
165        let trait_args = impl_
166            .of_trait
167            .into_iter()
168            .flat_map(|trait_ref| trait_ref.path.segments.last().unwrap().args().args)
169            .map(|arg| arg.span());
170        let dummy_spans_for_default_args =
171            impl_.of_trait.into_iter().flat_map(|trait_ref| iter::repeat(trait_ref.path.span));
172        iter::once(impl_.self_ty.span).chain(trait_args).chain(dummy_spans_for_default_args)
173    } else {
174        bug!("unexpected item for impl {def_id:?}: {item:?}")
175    }
176}