rustc_passes/
layout_test.rs1use 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};
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 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 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 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();
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 = tcx.normalize_erasing_regions(typing_env, ty);
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)
81 }
82 RustcDumpLayoutKind::HomogenousAggregate => {
83 let data =
84 ty_layout.homogeneous_aggregate(&UnwrapLayoutCx { tcx, typing_env });
85 ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("homogeneous_aggregate: {0:?}",
data))
})format!("homogeneous_aggregate: {data:?}")
86 }
87 RustcDumpLayoutKind::Size => ::alloc::__export::must_use({
::alloc::fmt::format(format_args!("size: {0:?}", ty_layout.size))
})format!("size: {:?}", ty_layout.size),
88 };
89 tcx.dcx().span_err(span, message);
90 }
91 }
92
93 Err(layout_error) => {
94 tcx.dcx().span_err(span, layout_error.to_string());
95 }
96 }
97}
98
99struct UnwrapLayoutCx<'tcx> {
100 tcx: TyCtxt<'tcx>,
101 typing_env: ty::TypingEnv<'tcx>,
102}
103
104impl<'tcx> LayoutOfHelpers<'tcx> for UnwrapLayoutCx<'tcx> {
105 fn handle_layout_err(&self, err: LayoutError<'tcx>, span: Span, ty: Ty<'tcx>) -> ! {
106 ::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!(
107 span,
108 "`#[rustc_dump_layout(..)]` test resulted in `layout_of({ty}) = Err({err})`",
109 );
110 }
111}
112
113impl<'tcx> HasTyCtxt<'tcx> for UnwrapLayoutCx<'tcx> {
114 fn tcx(&self) -> TyCtxt<'tcx> {
115 self.tcx
116 }
117}
118
119impl<'tcx> HasTypingEnv<'tcx> for UnwrapLayoutCx<'tcx> {
120 fn typing_env(&self) -> ty::TypingEnv<'tcx> {
121 self.typing_env
122 }
123}
124
125impl<'tcx> HasDataLayout for UnwrapLayoutCx<'tcx> {
126 fn data_layout(&self) -> &TargetDataLayout {
127 self.tcx.data_layout()
128 }
129}