Skip to main content

rustc_hir_analysis/collect/
dump.rs

1use rustc_hir as hir;
2use rustc_hir::def::DefKind;
3use rustc_hir::def_id::LocalDefId;
4use rustc_hir::{find_attr, intravisit};
5use rustc_middle::hir::nested_filter;
6use rustc_middle::ty::{self, TyCtxt, TypeVisitableExt, Unnormalized};
7use rustc_span::sym;
8
9pub(crate) fn opaque_hidden_types(tcx: TyCtxt<'_>) {
10    if !{
        'done:
            {
            for i in tcx.hir_krate_attrs() {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(RustcDumpHiddenTypeOfOpaques)
                        => {
                        break 'done Some(());
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }.is_some()find_attr!(tcx, crate, RustcDumpHiddenTypeOfOpaques) {
11        return;
12    }
13    for id in tcx.hir_crate_items(()).opaques() {
14        if let hir::OpaqueTyOrigin::FnReturn { parent: fn_def_id, .. }
15        | hir::OpaqueTyOrigin::AsyncFn { parent: fn_def_id, .. } =
16            tcx.hir_expect_opaque_ty(id).origin
17            && let hir::Node::TraitItem(trait_item) = tcx.hir_node_by_def_id(fn_def_id)
18            && let (_, hir::TraitFn::Required(..)) = trait_item.expect_fn()
19        {
20            continue;
21        }
22
23        let ty = tcx.type_of(id).instantiate_identity().skip_norm_wip();
24        let span = tcx.def_span(id);
25        tcx.dcx().emit_err(crate::errors::TypeOf { span, ty });
26    }
27}
28
29pub(crate) fn predicates_and_item_bounds(tcx: TyCtxt<'_>) {
30    for id in tcx.hir_crate_items(()).owners() {
31        #[expect(deprecated)] // we don't want to unnecessarily retrieve the attrs twice in a row.
32        let attrs = tcx.get_all_attrs(id);
33
34        if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(RustcDumpPredicates) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, RustcDumpPredicates) {
35            let preds = tcx
36                .predicates_of(id)
37                .instantiate_identity(tcx)
38                .predicates
39                .into_iter()
40                .map(Unnormalized::skip_norm_wip);
41            let span = tcx.def_span(id);
42
43            let mut diag = tcx.dcx().struct_span_err(span, sym::rustc_dump_predicates.as_str());
44            for pred in preds {
45                diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", pred))
    })format!("{pred:?}"));
46            }
47            diag.emit();
48        }
49
50        if {
    {
            'done:
                {
                for i in attrs {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(RustcDumpItemBounds) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }.is_some()
}find_attr!(attrs, RustcDumpItemBounds) {
51            let name = sym::rustc_dump_item_bounds.as_str();
52
53            match tcx.def_kind(id) {
54                DefKind::AssocTy => {
55                    let bounds = tcx.item_bounds(id).instantiate_identity().skip_norm_wip();
56                    let span = tcx.def_span(id);
57
58                    let mut diag = tcx.dcx().struct_span_err(span, name);
59                    for bound in bounds {
60                        diag.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", bound))
    })format!("{bound:?}"));
61                    }
62                    diag.emit()
63                }
64                kind => tcx.dcx().span_delayed_bug(
65                    tcx.def_span(id),
66                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("attr parsing didn\'t report an error for `#[{0}]` on {1:?}",
                name, kind))
    })format!("attr parsing didn't report an error for `#[{name}]` on {kind:?}"),
67                ),
68            };
69        }
70    }
71}
72
73pub(crate) fn def_parents(tcx: TyCtxt<'_>) {
74    for iid in tcx.hir_free_items() {
75        let did = iid.owner_id.def_id;
76        if {
        {
            'done:
                {
                for i in ::rustc_hir::attrs::HasAttrs::get_attrs(did, &tcx) {
                    #[allow(unused_imports)]
                    use rustc_hir::attrs::AttributeKind::*;
                    let i: &rustc_hir::Attribute = i;
                    match i {
                        rustc_hir::Attribute::Parsed(RustcDumpDefParents) => {
                            break 'done Some(());
                        }
                        rustc_hir::Attribute::Unparsed(..) =>
                            {}
                            #[deny(unreachable_patterns)]
                            _ => {}
                    }
                }
                None
            }
        }
    }.is_some()find_attr!(tcx, did, RustcDumpDefParents) {
77            struct AnonConstFinder<'tcx> {
78                tcx: TyCtxt<'tcx>,
79                anon_consts: Vec<LocalDefId>,
80            }
81
82            impl<'tcx> intravisit::Visitor<'tcx> for AnonConstFinder<'tcx> {
83                type NestedFilter = nested_filter::All;
84
85                fn maybe_tcx(&mut self) -> Self::MaybeTyCtxt {
86                    self.tcx
87                }
88
89                fn visit_anon_const(&mut self, c: &'tcx rustc_hir::AnonConst) {
90                    self.anon_consts.push(c.def_id);
91                    intravisit::walk_anon_const(self, c)
92                }
93            }
94
95            // Look for any anon consts inside of this item as there is no way to apply
96            // the `rustc_dump_def_parents` attribute to the anon const so it would not be possible
97            // to see what its def parent is.
98            let mut anon_ct_finder = AnonConstFinder { tcx, anon_consts: ::alloc::vec::Vec::new()vec![] };
99            intravisit::walk_item(&mut anon_ct_finder, tcx.hir_item(iid));
100
101            for did in [did].into_iter().chain(anon_ct_finder.anon_consts) {
102                let span = tcx.def_span(did);
103
104                let mut diag = tcx.dcx().struct_span_err(
105                    span,
106                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}: {1:?}",
                sym::rustc_dump_def_parents.as_str(), did))
    })format!("{}: {did:?}", sym::rustc_dump_def_parents.as_str()),
107                );
108
109                let mut current_did = did.to_def_id();
110                while let Some(parent_did) = tcx.opt_parent(current_did) {
111                    current_did = parent_did;
112                    diag.span_note(tcx.def_span(parent_did), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0:?}", parent_did))
    })format!("{parent_did:?}"));
113                }
114                diag.emit();
115            }
116        }
117    }
118}
119
120pub(crate) fn vtables<'tcx>(tcx: TyCtxt<'tcx>) {
121    for id in tcx.hir_free_items() {
122        let def_id = id.owner_id.def_id;
123
124        let Some(&attr_span) = {
    {
        'done:
            {
            for i in ::rustc_hir::attrs::HasAttrs::get_attrs(def_id, &tcx) {
                #[allow(unused_imports)]
                use rustc_hir::attrs::AttributeKind::*;
                let i: &rustc_hir::Attribute = i;
                match i {
                    rustc_hir::Attribute::Parsed(RustcDumpVtable(span)) => {
                        break 'done Some(span);
                    }
                    rustc_hir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, def_id, RustcDumpVtable(span) => span) else {
125            continue;
126        };
127
128        let vtable_entries = match tcx.hir_item(id).kind {
129            hir::ItemKind::Impl(hir::Impl { of_trait: Some(_), .. }) => {
130                let trait_ref = tcx.impl_trait_ref(def_id).instantiate_identity();
131                if trait_ref.skip_normalization().has_non_region_param() {
132                    tcx.dcx().span_err(
133                        attr_span,
134                        "`rustc_dump_vtable` must be applied to non-generic impl",
135                    );
136                    continue;
137                }
138                if !tcx.is_dyn_compatible(trait_ref.skip_normalization().def_id) {
139                    tcx.dcx().span_err(
140                        attr_span,
141                        "`rustc_dump_vtable` must be applied to dyn-compatible trait",
142                    );
143                    continue;
144                }
145                let Ok(trait_ref) = tcx
146                    .try_normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), trait_ref)
147                else {
148                    tcx.dcx().span_err(
149                        attr_span,
150                        "`rustc_dump_vtable` applied to impl header that cannot be normalized",
151                    );
152                    continue;
153                };
154                tcx.vtable_entries(trait_ref)
155            }
156            hir::ItemKind::TyAlias(..) => {
157                let ty = tcx.type_of(def_id).instantiate_identity();
158                if ty.skip_normalization().has_non_region_param() {
159                    tcx.dcx().span_err(
160                        attr_span,
161                        "`rustc_dump_vtable` must be applied to non-generic type",
162                    );
163                    continue;
164                }
165                let Ok(ty) =
166                    tcx.try_normalize_erasing_regions(ty::TypingEnv::fully_monomorphized(), ty)
167                else {
168                    tcx.dcx().span_err(
169                        attr_span,
170                        "`rustc_dump_vtable` applied to type alias that cannot be normalized",
171                    );
172                    continue;
173                };
174                let ty::Dynamic(data, _) = *ty.kind() else {
175                    tcx.dcx().span_err(attr_span, "`rustc_dump_vtable` to type alias of dyn type");
176                    continue;
177                };
178                if let Some(principal) = data.principal() {
179                    tcx.vtable_entries(
180                        tcx.instantiate_bound_regions_with_erased(principal).with_self_ty(tcx, ty),
181                    )
182                } else {
183                    TyCtxt::COMMON_VTABLE_ENTRIES
184                }
185            }
186            _ => {
187                tcx.dcx().span_err(
188                    attr_span,
189                    "`rustc_dump_vtable` only applies to impl, or type alias of dyn type",
190                );
191                continue;
192            }
193        };
194
195        tcx.dcx().span_err(tcx.def_span(def_id), ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("vtable entries: {0:#?}",
                vtable_entries))
    })format!("vtable entries: {vtable_entries:#?}"));
196    }
197}