Skip to main content

rustc_passes/
layout_test.rs

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