Skip to main content

rustc_passes/
layout_test.rs

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