Skip to main content

rustc_ty_utils/
assoc.rs

1use rustc_hir::def::DefKind;
2use rustc_hir::def_id::{DefId, DefIdMap, LocalDefId};
3use rustc_hir::definitions::{DefPathData, PerParentDisambiguatorState};
4use rustc_hir::intravisit::{self, Visitor};
5use rustc_hir::{self as hir, Generics, ImplItemImplKind, ItemKind};
6use rustc_middle::query::Providers;
7use rustc_middle::ty::{self, ImplTraitInTraitData, TyCtxt};
8use rustc_span::symbol::kw;
9use rustc_span::{Ident, bug, span_bug};
10
11pub(crate) fn provide(providers: &mut Providers) {
12    *providers = Providers {
13        associated_item,
14        associated_item_def_ids,
15        associated_items,
16        associated_types_for_impl_traits_in_trait_or_impl,
17        impl_item_implementor_ids,
18        ..*providers
19    };
20}
21
22fn associated_item_def_ids(tcx: TyCtxt<'_>, def_id: LocalDefId) -> &[DefId] {
23    let item = tcx.hir_expect_item(def_id);
24    match item.kind {
25        hir::ItemKind::Trait { items: trait_item_refs, .. } => {
26            // We collect RPITITs for each trait method's return type and create a corresponding
27            // associated item using the associated_types_for_impl_traits_in_trait_or_impl
28            // query.
29            let rpitit_items = tcx.associated_types_for_impl_traits_in_trait_or_impl(def_id);
30            tcx.arena.alloc_from_iter(trait_item_refs.iter().flat_map(|trait_item_ref| {
31                let item_def_id = trait_item_ref.owner_id.to_def_id();
32                [item_def_id]
33                    .into_iter()
34                    .chain(rpitit_items.get(&item_def_id).into_flat_iter().copied())
35            }))
36        }
37        hir::ItemKind::Impl(impl_) => {
38            // We collect RPITITs for each trait method's return type, on the impl side too and
39            // create a corresponding associated item using
40            // associated_types_for_impl_traits_in_trait_or_impl query.
41            let rpitit_items = tcx.associated_types_for_impl_traits_in_trait_or_impl(def_id);
42            tcx.arena.alloc_from_iter(impl_.items.iter().flat_map(|impl_item_ref| {
43                let item_def_id = impl_item_ref.owner_id.to_def_id();
44                [item_def_id]
45                    .into_iter()
46                    .chain(rpitit_items.get(&item_def_id).into_flat_iter().copied())
47            }))
48        }
49        _ => ::rustc_span::macros::bug_impl(Some(item.span),
    format_args!("associated_item_def_ids: not impl or trait"),
    Location::caller())span_bug!(item.span, "associated_item_def_ids: not impl or trait"),
50    }
51}
52
53fn associated_items(tcx: TyCtxt<'_>, def_id: DefId) -> ty::AssocItems {
54    if tcx.is_trait_alias(def_id) {
55        ty::AssocItems::new(Vec::new())
56    } else {
57        let items = tcx.associated_item_def_ids(def_id).iter().map(|did| tcx.associated_item(*did));
58        ty::AssocItems::new(items)
59    }
60}
61
62fn impl_item_implementor_ids(tcx: TyCtxt<'_>, impl_id: DefId) -> DefIdMap<DefId> {
63    tcx.associated_items(impl_id)
64        .in_definition_order()
65        .filter_map(|item| item.trait_item_def_id().map(|trait_item| (trait_item, item.def_id)))
66        .collect()
67}
68
69fn associated_item(tcx: TyCtxt<'_>, def_id: LocalDefId) -> ty::AssocItem {
70    let assoc_item = match tcx.hir_node_by_def_id(def_id) {
71        hir::Node::TraitItem(ti) => associated_item_from_trait_item(tcx, ti),
72        hir::Node::ImplItem(ii) => associated_item_from_impl_item(tcx, ii),
73        node => ::rustc_span::macros::bug_impl(Some(tcx.def_span(def_id)),
    format_args!("impl item or item not found: {0:?}", node),
    Location::caller())span_bug!(tcx.def_span(def_id), "impl item or item not found: {:?}", node,),
74    };
75    if true {
    {
        match (&assoc_item.def_id.expect_local(), &def_id) {
            (left_val, right_val) => {
                if !(*left_val == *right_val) {
                    let kind = ::core::panicking::AssertKind::Eq;
                    ::core::panicking::assert_failed(kind, &*left_val,
                        &*right_val, ::core::option::Option::None);
                }
            }
        }
    };
};debug_assert_eq!(assoc_item.def_id.expect_local(), def_id);
76    assoc_item
77}
78
79fn fn_has_self_parameter(tcx: TyCtxt<'_>, owner_id: hir::OwnerId, generics: &Generics<'_>) -> bool {
80    // With `function_arg_const_generics`, const parameters are moved into the
81    // generics. We check the original `arg_pos` to avoid treating a later `self`
82    // as a valid receiver after the const parameters are removed.
83    #[allow(non_exhaustive_omitted_patterns)] match tcx.fn_arg_idents(owner_id.def_id)
    {
    [Some(Ident { name: kw::SelfLower, .. }), ..] => true,
    _ => false,
}matches!(tcx.fn_arg_idents(owner_id.def_id), [Some(Ident { name: kw::SelfLower, .. }), ..])
84        && !generics.params.iter().any(|param| {
85            #[allow(non_exhaustive_omitted_patterns)] match param.kind {
    hir::GenericParamKind::Const { arg_pos: Some(0), .. } => true,
    _ => false,
}matches!(param.kind, hir::GenericParamKind::Const { arg_pos: Some(0), .. })
86        })
87}
88
89fn associated_item_from_trait_item(
90    tcx: TyCtxt<'_>,
91    trait_item: &hir::TraitItem<'_>,
92) -> ty::AssocItem {
93    let owner_id = trait_item.owner_id;
94    let name = trait_item.ident.name;
95    let kind = match trait_item.kind {
96        hir::TraitItemKind::Const(_, _) => {
97            ty::AssocKind::Const { data: ty::AssocConstData::Named(name) }
98        }
99        hir::TraitItemKind::Fn { .. } => ty::AssocKind::Fn {
100            name,
101            has_self: fn_has_self_parameter(tcx, owner_id, trait_item.generics),
102        },
103        hir::TraitItemKind::Type { .. } => {
104            ty::AssocKind::Type { data: ty::AssocTypeData::Normal(name) }
105        }
106    };
107
108    ty::AssocItem { kind, def_id: owner_id.to_def_id(), container: ty::AssocContainer::Trait }
109}
110
111fn associated_item_from_impl_item(tcx: TyCtxt<'_>, impl_item: &hir::ImplItem<'_>) -> ty::AssocItem {
112    let owner_id = impl_item.owner_id;
113    let name = impl_item.ident.name;
114    let kind = match impl_item.kind {
115        hir::ImplItemKind::Const(..) => {
116            let data = if impl_item.is_anon_const() {
117                ty::AssocConstData::Anonymous
118            } else {
119                ty::AssocConstData::Named(name)
120            };
121            ty::AssocKind::Const { data }
122        }
123        hir::ImplItemKind::Fn(..) => ty::AssocKind::Fn {
124            name,
125            has_self: fn_has_self_parameter(tcx, owner_id, impl_item.generics),
126        },
127        hir::ImplItemKind::Type(..) => {
128            ty::AssocKind::Type { data: ty::AssocTypeData::Normal(name) }
129        }
130    };
131
132    let container = match impl_item.impl_kind {
133        ImplItemImplKind::Inherent { .. } => ty::AssocContainer::InherentImpl,
134        ImplItemImplKind::Trait { trait_item_def_id, .. } => {
135            ty::AssocContainer::TraitImpl(trait_item_def_id)
136        }
137    };
138    ty::AssocItem { kind, def_id: owner_id.to_def_id(), container }
139}
140struct RPITVisitor<'a, 'tcx> {
141    tcx: TyCtxt<'tcx>,
142    synthetics: Vec<LocalDefId>,
143    data: DefPathData,
144    disambiguator: &'a mut PerParentDisambiguatorState,
145}
146
147impl<'tcx> Visitor<'tcx> for RPITVisitor<'_, 'tcx> {
148    fn visit_opaque_ty(&mut self, opaque: &'tcx hir::OpaqueTy<'tcx>) -> Self::Result {
149        self.synthetics.push(associated_type_for_impl_trait_in_trait(
150            self.tcx,
151            opaque.def_id,
152            self.data,
153            &mut self.disambiguator,
154        ));
155        intravisit::walk_opaque_ty(self, opaque)
156    }
157}
158
159fn associated_types_for_impl_traits_in_trait_or_impl<'tcx>(
160    tcx: TyCtxt<'tcx>,
161    def_id: LocalDefId,
162) -> DefIdMap<Vec<DefId>> {
163    let item = tcx.hir_expect_item(def_id);
164    let disambiguator = &mut PerParentDisambiguatorState::new(def_id);
165    match item.kind {
166        ItemKind::Trait { items: trait_item_refs, .. } => trait_item_refs
167            .iter()
168            .filter_map(move |item| {
169                if !#[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(item.owner_id) {
    DefKind::AssocFn => true,
    _ => false,
}matches!(tcx.def_kind(item.owner_id), DefKind::AssocFn) {
170                    return None;
171                }
172                let fn_def_id = item.owner_id.def_id;
173                let Some(output) = tcx.hir_get_fn_output(fn_def_id) else {
174                    return Some((fn_def_id.to_def_id(), ::alloc::vec::Vec::new()vec![]));
175                };
176                let def_name = tcx.item_name(fn_def_id.to_def_id());
177                let data = DefPathData::AnonAssocTy(def_name);
178                let mut visitor = RPITVisitor { tcx, synthetics: ::alloc::vec::Vec::new()vec![], data, disambiguator };
179                visitor.visit_fn_ret_ty(output);
180                let defs = visitor
181                    .synthetics
182                    .into_iter()
183                    .map(|def_id| def_id.to_def_id())
184                    .collect::<Vec<_>>();
185                Some((fn_def_id.to_def_id(), defs))
186            })
187            .collect(),
188        ItemKind::Impl(impl_) => {
189            let Some(of_trait) = impl_.of_trait else {
190                return Default::default();
191            };
192            let Some(trait_def_id) = of_trait.trait_ref.trait_def_id() else {
193                return Default::default();
194            };
195            let in_trait_def = tcx.associated_types_for_impl_traits_in_trait_or_impl(trait_def_id);
196            impl_
197                .items
198                .iter()
199                .filter_map(|item| {
200                    if !#[allow(non_exhaustive_omitted_patterns)] match tcx.def_kind(item.owner_id) {
    DefKind::AssocFn => true,
    _ => false,
}matches!(tcx.def_kind(item.owner_id), DefKind::AssocFn) {
201                        return None;
202                    }
203                    let did = item.owner_id.def_id.to_def_id();
204                    let item = tcx.hir_impl_item(*item);
205                    let ImplItemImplKind::Trait {
206                        trait_item_def_id: Ok(trait_item_def_id), ..
207                    } = item.impl_kind
208                    else {
209                        return Some((did, ::alloc::vec::Vec::new()vec![]));
210                    };
211                    let iter = in_trait_def[&trait_item_def_id].iter().map(|&id| {
212                        associated_type_for_impl_trait_in_impl(tcx, id, item, disambiguator)
213                            .to_def_id()
214                    });
215                    Some((did, iter.collect()))
216                })
217                .collect()
218        }
219        _ => {
220            ::rustc_span::macros::bug_impl(None,
    format_args!("associated_types_for_impl_traits_in_trait_or_impl: {0:?} should be Trait or Impl but is {1:?}",
        def_id, tcx.def_kind(def_id)), Location::caller())bug!(
221                "associated_types_for_impl_traits_in_trait_or_impl: {:?} should be Trait or Impl but is {:?}",
222                def_id,
223                tcx.def_kind(def_id)
224            )
225        }
226    }
227}
228
229/// Given an `opaque_ty_def_id` corresponding to an `impl Trait` in an associated
230/// function from a trait, synthesize an associated type for that `impl Trait`
231/// that inherits properties that we infer from the method and the opaque type.
232fn associated_type_for_impl_trait_in_trait(
233    tcx: TyCtxt<'_>,
234    opaque_ty_def_id: LocalDefId,
235    data: DefPathData,
236    disambiguator: &mut PerParentDisambiguatorState,
237) -> LocalDefId {
238    let (hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }
239    | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. }) =
240        tcx.local_opaque_ty_origin(opaque_ty_def_id)
241    else {
242        ::rustc_span::macros::bug_impl(None,
    format_args!("expected opaque for {0:?}", opaque_ty_def_id),
    Location::caller());bug!("expected opaque for {opaque_ty_def_id:?}");
243    };
244    let trait_def_id = tcx.local_parent(fn_def_id);
245    {
    match (&tcx.def_kind(trait_def_id), &DefKind::Trait) {
        (left_val, right_val) => {
            if !(*left_val == *right_val) {
                let kind = ::core::panicking::AssertKind::Eq;
                ::core::panicking::assert_failed(kind, &*left_val,
                    &*right_val, ::core::option::Option::None);
            }
        }
    }
};assert_eq!(tcx.def_kind(trait_def_id), DefKind::Trait);
246
247    let span = tcx.def_span(opaque_ty_def_id);
248    // Also use the method name to create an unique def path.
249    let trait_assoc_ty = tcx.at(span).create_def(
250        trait_def_id,
251        // No name because this is an anonymous associated type.
252        None,
253        DefKind::AssocTy,
254        Some(data),
255        disambiguator,
256    );
257
258    let local_def_id = trait_assoc_ty.def_id();
259    let def_id = local_def_id.to_def_id();
260
261    trait_assoc_ty.feed_hir();
262
263    // Copy span of the opaque.
264    trait_assoc_ty.def_ident_span(Some(span));
265
266    trait_assoc_ty.associated_item(ty::AssocItem {
267        kind: ty::AssocKind::Type {
268            data: ty::AssocTypeData::Rpitit(ImplTraitInTraitData::Trait {
269                fn_def_id: fn_def_id.to_def_id(),
270                opaque_def_id: opaque_ty_def_id.to_def_id(),
271            }),
272        },
273        def_id,
274        container: ty::AssocContainer::Trait,
275    });
276
277    // Copy visility of the containing function.
278    trait_assoc_ty.visibility(tcx.visibility(fn_def_id));
279
280    // Copy defaultness of the containing function.
281    trait_assoc_ty.defaultness(tcx.defaultness(fn_def_id));
282
283    // There are no inferred outlives for the synthesized associated type.
284    trait_assoc_ty.inferred_outlives_of(&[]);
285
286    local_def_id
287}
288
289/// Given an `trait_assoc_def_id` corresponding to an associated item synthesized
290/// from an `impl Trait` in an associated function from a trait, and an
291/// `impl_fn` that represents an implementation of the associated function
292/// that the `impl Trait` comes from, synthesize an associated type for that `impl Trait`
293/// that inherits properties that we infer from the method and the associated type.
294fn associated_type_for_impl_trait_in_impl(
295    tcx: TyCtxt<'_>,
296    trait_assoc_def_id: DefId,
297    impl_fn: &hir::ImplItem<'_>,
298    disambiguator: &mut PerParentDisambiguatorState,
299) -> LocalDefId {
300    let impl_local_def_id = tcx.local_parent(impl_fn.owner_id.def_id);
301
302    let hir::ImplItemKind::Fn(fn_sig, _) = impl_fn.kind else { ::rustc_span::macros::bug_impl(None, format_args!("expected decl"),
    Location::caller())bug!("expected decl") };
303    let span = match fn_sig.decl.output {
304        hir::FnRetTy::DefaultReturn(_) => tcx.def_span(impl_fn.owner_id),
305        hir::FnRetTy::Return(ty) => ty.span,
306    };
307
308    // Use the same disambiguator and method name as the anon associated type in the trait.
309    let disambiguated_data = tcx.def_key(trait_assoc_def_id).disambiguated_data;
310    let DefPathData::AnonAssocTy(name) = disambiguated_data.data else {
311        ::rustc_span::macros::bug_impl(None,
    format_args!("expected anon associated type"), Location::caller())bug!("expected anon associated type")
312    };
313    let data = DefPathData::AnonAssocTy(name);
314
315    let impl_assoc_ty = tcx.at(span).create_def(
316        impl_local_def_id,
317        // No name because this is an anonymous associated type.
318        None,
319        DefKind::AssocTy,
320        Some(data),
321        disambiguator,
322    );
323
324    let local_def_id = impl_assoc_ty.def_id();
325    let def_id = local_def_id.to_def_id();
326
327    impl_assoc_ty.feed_hir();
328
329    // Copy span of the opaque.
330    impl_assoc_ty.def_ident_span(Some(span));
331
332    impl_assoc_ty.associated_item(ty::AssocItem {
333        kind: ty::AssocKind::Type {
334            data: ty::AssocTypeData::Rpitit(ImplTraitInTraitData::Impl {
335                fn_def_id: impl_fn.owner_id.to_def_id(),
336            }),
337        },
338        def_id,
339        container: ty::AssocContainer::TraitImpl(Ok(trait_assoc_def_id)),
340    });
341
342    // Copy visility of the containing function.
343    impl_assoc_ty.visibility(tcx.visibility(impl_fn.owner_id));
344
345    // Copy defaultness of the containing function.
346    impl_assoc_ty.defaultness(tcx.defaultness(impl_fn.owner_id));
347
348    // Copy generics_of the trait's associated item but the impl as the parent.
349    // FIXME: This may be detrimental to diagnostics, as we resolve the early-bound vars
350    // here to paramswhose parent are items in the trait. We could synthesize new params
351    // here, but it seems overkill.
352    impl_assoc_ty.generics_of({
353        let trait_assoc_generics = tcx.generics_of(trait_assoc_def_id);
354        let trait_assoc_parent_count = trait_assoc_generics.parent_count;
355        let mut own_params = trait_assoc_generics.own_params.clone();
356
357        let parent_generics = tcx.generics_of(impl_local_def_id.to_def_id());
358        let parent_count = parent_generics.count();
359
360        for param in &mut own_params {
361            param.index = param.index + parent_count as u32 - trait_assoc_parent_count as u32;
362        }
363
364        let param_def_id_to_index =
365            own_params.iter().map(|param| (param.def_id, param.index)).collect();
366
367        ty::Generics {
368            parent: Some(impl_local_def_id.to_def_id()),
369            parent_count,
370            own_params,
371            param_def_id_to_index,
372            has_self: false,
373            has_arg_pos_consts: trait_assoc_generics.has_arg_pos_consts,
374            has_late_bound_regions: trait_assoc_generics.has_late_bound_regions,
375        }
376    });
377
378    // There are no inferred outlives for the synthesized associated type.
379    impl_assoc_ty.inferred_outlives_of(&[]);
380
381    local_def_id
382}