Skip to main content

rustc_passes/
layout_test.rs

1use rustc_abi::{HasDataLayout, TargetDataLayout};
2use rustc_attr_ir::{RustcDumpLayoutKind, find_attr};
3use rustc_hir::def::DefKind;
4use rustc_hir::def_id::LocalDefId;
5use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutError, LayoutOfHelpers};
6use rustc_middle::ty::{self, Ty, TyCtxt, Unnormalized};
7use rustc_span::{Span, span_bug};
8use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
9use rustc_trait_selection::infer::TyCtxtInferExt;
10use rustc_trait_selection::traits::{self, TraitErrors};
11
12pub fn test_layout(tcx: TyCtxt<'_>) {
13    if !tcx.features().rustc_attrs() {
14        // if the `rustc_attrs` feature is not enabled, don't bother testing layout
15        return;
16    }
17    for id in tcx.hir_crate_items(()).definitions() {
18        if let Some(kinds) = {
    {
        'done:
            {
            for i in ::rustc_attr_ir::HasAttrs::get_attrs(id, &tcx) {
                #[allow(unused_imports)]
                use ::rustc_attr_ir::AttributeKind::*;
                let i: &::rustc_attr_ir::Attribute = i;
                match i {
                    ::rustc_attr_ir::Attribute::Parsed(RustcDumpLayout(kinds))
                        => {
                        break 'done Some(kinds);
                    }
                    ::rustc_attr_ir::Attribute::Unparsed(..) =>
                        {}
                        #[deny(unreachable_patterns)]
                        _ => {}
                }
            }
            None
        }
    }
}find_attr!(tcx, id, RustcDumpLayout(kinds) => kinds) {
19            // Attribute parsing handles error reporting
20            if let DefKind::TyAlias | DefKind::Enum | DefKind::Struct | DefKind::Union =
21                tcx.def_kind(id)
22            {
23                dump_layout_of(tcx, id, kinds);
24            }
25        }
26    }
27}
28
29pub fn ensure_wf<'tcx>(
30    tcx: TyCtxt<'tcx>,
31    typing_env: ty::TypingEnv<'tcx>,
32    ty: Ty<'tcx>,
33    def_id: LocalDefId,
34    span: Span,
35) -> bool {
36    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
37    let ocx = traits::ObligationCtxt::new_with_diagnostics(&infcx);
38    let pred = ty::ClauseKind::WellFormed(ty.into());
39    let obligation = traits::Obligation::new(
40        tcx,
41        traits::ObligationCause::new(
42            span,
43            def_id,
44            traits::ObligationCauseCode::WellFormed(Some(traits::WellFormedLoc::Ty(def_id))),
45        ),
46        param_env,
47        pred,
48    );
49    ocx.register_obligation(obligation);
50    let errors = ocx.evaluate_obligations_error_on_ambiguity();
51    if let TraitErrors::HasErrors(errors) = errors {
52        infcx.err_ctxt().report_fulfillment_errors(errors);
53        false
54    } else {
55        // looks WF!
56        true
57    }
58}
59
60fn dump_layout_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId, kinds: &[RustcDumpLayoutKind]) {
61    let typing_env = ty::TypingEnv::codegen(tcx, item_def_id);
62    let ty = tcx.type_of(item_def_id).instantiate_identity().skip_norm_wip();
63    let span = tcx.def_span(item_def_id.to_def_id());
64    if !ensure_wf(tcx, typing_env, ty, item_def_id, span) {
65        return;
66    }
67    match tcx.layout_of(typing_env.as_query_input(ty)) {
68        Ok(ty_layout) => {
69            for kind in kinds {
70                let message = match kind {
71                    RustcDumpLayoutKind::Align => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("align: {0:?}", *ty_layout.align))
    })format!("align: {:?}", *ty_layout.align),
72                    RustcDumpLayoutKind::BackendRepr => {
73                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("backend_repr: {0:?}",
                ty_layout.backend_repr))
    })format!("backend_repr: {:?}", ty_layout.backend_repr)
74                    }
75                    RustcDumpLayoutKind::Debug => {
76                        let normalized_ty =
77                            tcx.normalize_erasing_regions(typing_env, Unnormalized::new_wip(ty));
78                        // FIXME: using the `Debug` impl here isn't ideal.
79                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("layout_of({1}) = {0:#?}",
                *ty_layout, normalized_ty))
    })format!("layout_of({normalized_ty}) = {:#?}", *ty_layout)
80                    }
81                    RustcDumpLayoutKind::HomogenousAggregate => {
82                        let data =
83                            ty_layout.homogeneous_aggregate(&UnwrapLayoutCx { tcx, typing_env });
84                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("homogeneous_aggregate: {0:?}",
                data))
    })format!("homogeneous_aggregate: {data:?}")
85                    }
86                    RustcDumpLayoutKind::LargestNiche => {
87                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("largest_niche: {0:?}",
                ty_layout.largest_niche))
    })format!("largest_niche: {:?}", ty_layout.largest_niche)
88                    }
89                    RustcDumpLayoutKind::Size => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("size: {0:?}", ty_layout.size))
    })format!("size: {:?}", ty_layout.size),
90                };
91                tcx.dcx().span_err(span, message);
92            }
93        }
94
95        Err(layout_error) => {
96            tcx.dcx().span_err(span, layout_error.to_string());
97        }
98    }
99}
100
101struct UnwrapLayoutCx<'tcx> {
102    tcx: TyCtxt<'tcx>,
103    typing_env: ty::TypingEnv<'tcx>,
104}
105
106impl<'tcx> LayoutOfHelpers<'tcx> for UnwrapLayoutCx<'tcx> {
107    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
108        ::rustc_span::macros::bug_impl(Some(span),
    format_args!("`#[rustc_dump_layout(..)]` test resulted in `layout_of({0}) = Err({1})`",
        ty, err), Location::caller());span_bug!(
109            span,
110            "`#[rustc_dump_layout(..)]` test resulted in `layout_of({ty}) = Err({err})`",
111        );
112    }
113}
114
115impl<'tcx> HasTyCtxt<'tcx> for UnwrapLayoutCx<'tcx> {
116    fn tcx(&self) -> TyCtxt<'tcx> {
117        self.tcx
118    }
119}
120
121impl<'tcx> HasTypingEnv<'tcx> for UnwrapLayoutCx<'tcx> {
122    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
123        self.typing_env
124    }
125}
126
127impl<'tcx> HasDataLayout for UnwrapLayoutCx<'tcx> {
128    fn data_layout(&self) -> &TargetDataLayout {
129        self.tcx.data_layout()
130    }
131}