rustc_passes/
layout_test.rs

1use rustc_abi::{HasDataLayout, TargetDataLayout};
2use rustc_hir::Attribute;
3use rustc_hir::def::DefKind;
4use rustc_hir::def_id::LocalDefId;
5use rustc_middle::span_bug;
6use rustc_middle::ty::layout::{HasTyCtxt, HasTypingEnv, LayoutError, LayoutOfHelpers};
7use rustc_middle::ty::{self, Ty, TyCtxt};
8use rustc_span::source_map::Spanned;
9use rustc_span::{Span, sym};
10use rustc_trait_selection::error_reporting::InferCtxtErrorExt;
11use rustc_trait_selection::infer::TyCtxtInferExt;
12use rustc_trait_selection::traits;
13
14use crate::errors::{
15    LayoutAbi, LayoutAlign, LayoutHomogeneousAggregate, LayoutInvalidAttribute, LayoutOf,
16    LayoutSize, UnrecognizedField,
17};
18
19pub fn test_layout(tcx: TyCtxt<'_>) {
20    if !tcx.features().rustc_attrs() {
21        // if the `rustc_attrs` feature is not enabled, don't bother testing layout
22        return;
23    }
24    for id in tcx.hir_crate_items(()).definitions() {
25        for attr in tcx.get_attrs(id, sym::rustc_layout) {
26            match tcx.def_kind(id) {
27                DefKind::TyAlias | DefKind::Enum | DefKind::Struct | DefKind::Union => {
28                    dump_layout_of(tcx, id, attr);
29                }
30                _ => {
31                    tcx.dcx().emit_err(LayoutInvalidAttribute { span: tcx.def_span(id) });
32                }
33            }
34        }
35    }
36}
37
38pub fn ensure_wf<'tcx>(
39    tcx: TyCtxt<'tcx>,
40    typing_env: ty::TypingEnv<'tcx>,
41    ty: Ty<'tcx>,
42    def_id: LocalDefId,
43    span: Span,
44) -> bool {
45    let (infcx, param_env) = tcx.infer_ctxt().build_with_typing_env(typing_env);
46    let ocx = traits::ObligationCtxt::new_with_diagnostics(&infcx);
47    let pred = ty::ClauseKind::WellFormed(ty.into());
48    let obligation = traits::Obligation::new(
49        tcx,
50        traits::ObligationCause::new(
51            span,
52            def_id,
53            traits::ObligationCauseCode::WellFormed(Some(traits::WellFormedLoc::Ty(def_id))),
54        ),
55        param_env,
56        pred,
57    );
58    ocx.register_obligation(obligation);
59    let errors = ocx.select_all_or_error();
60    if !errors.is_empty() {
61        infcx.err_ctxt().report_fulfillment_errors(errors);
62        false
63    } else {
64        // looks WF!
65        true
66    }
67}
68
69fn dump_layout_of(tcx: TyCtxt<'_>, item_def_id: LocalDefId, attr: &Attribute) {
70    let typing_env = ty::TypingEnv::post_analysis(tcx, item_def_id);
71    let ty = tcx.type_of(item_def_id).instantiate_identity();
72    let span = tcx.def_span(item_def_id.to_def_id());
73    if !ensure_wf(tcx, typing_env, ty, item_def_id, span) {
74        return;
75    }
76    match tcx.layout_of(typing_env.as_query_input(ty)) {
77        Ok(ty_layout) => {
78            // Check out the `#[rustc_layout(..)]` attribute to tell what to dump.
79            // The `..` are the names of fields to dump.
80            let meta_items = attr.meta_item_list().unwrap_or_default();
81            for meta_item in meta_items {
82                match meta_item.name_or_empty() {
83                    // FIXME: this never was about ABI and now this dump arg is confusing
84                    sym::abi => {
85                        tcx.dcx().emit_err(LayoutAbi {
86                            span,
87                            abi: format!("{:?}", ty_layout.backend_repr),
88                        });
89                    }
90
91                    sym::align => {
92                        tcx.dcx().emit_err(LayoutAlign {
93                            span,
94                            align: format!("{:?}", ty_layout.align),
95                        });
96                    }
97
98                    sym::size => {
99                        tcx.dcx()
100                            .emit_err(LayoutSize { span, size: format!("{:?}", ty_layout.size) });
101                    }
102
103                    sym::homogeneous_aggregate => {
104                        tcx.dcx().emit_err(LayoutHomogeneousAggregate {
105                            span,
106                            homogeneous_aggregate: format!(
107                                "{:?}",
108                                ty_layout
109                                    .homogeneous_aggregate(&UnwrapLayoutCx { tcx, typing_env })
110                            ),
111                        });
112                    }
113
114                    sym::debug => {
115                        let normalized_ty =
116                            format!("{}", tcx.normalize_erasing_regions(typing_env, ty));
117                        // FIXME: using the `Debug` impl here isn't ideal.
118                        let ty_layout = format!("{:#?}", *ty_layout);
119                        tcx.dcx().emit_err(LayoutOf { span, normalized_ty, ty_layout });
120                    }
121
122                    name => {
123                        tcx.dcx().emit_err(UnrecognizedField { span: meta_item.span(), name });
124                    }
125                }
126            }
127        }
128
129        Err(layout_error) => {
130            tcx.dcx().emit_err(Spanned { node: layout_error.into_diagnostic(), span });
131        }
132    }
133}
134
135struct UnwrapLayoutCx<'tcx> {
136    tcx: TyCtxt<'tcx>,
137    typing_env: ty::TypingEnv<'tcx>,
138}
139
140impl<'tcx> LayoutOfHelpers<'tcx> for UnwrapLayoutCx<'tcx> {
141    fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
142        span_bug!(span, "`#[rustc_layout(..)]` test resulted in `layout_of({ty}) = Err({err})`",);
143    }
144}
145
146impl<'tcx> HasTyCtxt<'tcx> for UnwrapLayoutCx<'tcx> {
147    fn tcx(&self) -> TyCtxt<'tcx> {
148        self.tcx
149    }
150}
151
152impl<'tcx> HasTypingEnv<'tcx> for UnwrapLayoutCx<'tcx> {
153    fn typing_env(&self) -> ty::TypingEnv<'tcx> {
154        self.typing_env
155    }
156}
157
158impl<'tcx> HasDataLayout for UnwrapLayoutCx<'tcx> {
159    fn data_layout(&self) -> &TargetDataLayout {
160        self.tcx.data_layout()
161    }
162}