Skip to main content

rustc_passes/
layout_test.rs

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