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